Skip to content

Swiggy Bytes: Delivery Routing, Search and Peak Traffic

Advanced 131 min read Part 18 of 18

How Swiggy promises, batches and routes hyperlocal deliveries: serviceability at 200M checks a minute, geo, ETA models, CDC, Kafka, search and trade-offs.

Summary#

Swiggy is an Indian on-demand delivery company. It started with restaurant food in 2014 and grew into groceries in minutes (Instamart), pick-up-and-drop errands (Genie) and more, in hundreds of cities. Its fleet of delivery executives (DEs, the riders on two-wheelers) runs into the hundreds of thousands. An order is promised, assigned, picked up and dropped within 20 to 45 minutes, inside a few kilometres of the restaurant. That is what "hyperlocal" means: the whole business happens inside a small circle around each customer, and every circle behaves differently.

Swiggy's engineering blog, Swiggy Bytes, explains the systems behind that promise. The posts are unusually concrete about the maths and the compromises. They show a delivery-time equation, an assignment problem that is NP-hard, a serviceability platform that runs about 200 million distance checks a minute, and in-house OpenStreetMap routing tuned for motorcycles. They also cover machine-learning models that predict every leg of an order, the data infrastructure underneath (change data capture, Kafka, Redis, DynamoDB), and the customer-facing systems (feed ranking, search, experimentation, notifications, payments).

This page studies the posts in six families:

  • The delivery promise and assignment: the delivery-time equation, just-in-time assignment, batching as vehicle routing, and logistic zones learned with embeddings.
  • Serviceability, distance and geo: what "can we deliver here?" really means, the platform that answers it at peak, the OpenStreetMap distance service and Tile38 geo queries.
  • The logistics platform: re-architecting a delivery monolith into a task-job-trip platform, Instamart's assignment and routing, and real-time supply shaping.
  • Predictions: the delivery time shown at cart, the live "where is my order" ETA, and a hyperlocal forecasting platform.
  • Data and reliability infrastructure: CDC into Delta Lake, a Kafka client bug that took down 18 services, Redis pipelining, a guard rail for DynamoDB on-demand costs, and adaptive timeouts for microservices.
  • Customer-facing systems: feed ranking, search and autocomplete, the XP experimentation platform, the Kabootar communication platform, client-side caching and tracking, the delivery partner app, and ML-based payment routing.

A final family pulls the lessons together into Swiggy's recurring trade-offs.

Why It Exists#

Food delivery looks simple: take an order, send a rider, deliver. At Swiggy's scale it is one of the hardest real-time optimisation problems in consumer technology, for reasons a whiteboard design misses:

  • The product is a promise. The customer chooses a restaurant partly on the delivery time shown before ordering. If the promise is too short, food arrives late and trust drops. If it is too long, the customer orders elsewhere. The promise must be right for each restaurant, at each minute, at each address.
  • Three sides must be balanced. Customers, restaurants and DEs all have their own goals. A DE waiting at a restaurant is paid but idle. A restaurant whose food goes cold gets bad ratings. A customer who waits too long cancels.
  • Supply and demand change by the minute. Dinner peaks between 8 and 10 PM. Rain makes riders log off just when orders jump. A cricket final can change demand in one area while leaving the next unchanged.
  • Maps are not good enough. Commercial map services assume cars, charge per call, and do not know the "last last mile": the 5 to 10 minutes from the apartment gate, through security and lifts, to the door.
  • Every screen is a computation. Opening the app triggers geo-filtering, distance calculations, delivery-time predictions and surge decisions for thousands of restaurants, in a fraction of a second.

The textbook pages (geospatial indexing, the food delivery case study, change data capture, Redis) explain the building blocks. Swiggy's posts show how they combine under hard latency, cost and accuracy constraints, and what the engineers gave up each time.

How It Works#

The diagram shows where each family sits in one order's life. Before the order, the app asks the listing and search systems for restaurants. Serviceability filters them by geography, road distance, fleet stress and predicted delivery time. At the cart, an ML model fixes the promised delivery time. After the order, the logistics platform turns it into tasks and jobs. The assignment engine batches orders and assigns DEs just in time. The tracking ETA updates as the DE moves. Under all of this, CDC streams database changes to the lake, Kafka carries events between more than 50 services in the fulfilment path, and Kabootar sends notifications.

The lessons follow the families in order. Each covers one post, or a few closely linked posts. Each states the assumptions about traffic, latency, consistency and maintenance, then the design, the constraints that are easy to overlook, and what Swiggy sacrificed.

Family 1: The delivery promise and assignment

Lesson 1: The delivery challenge, part one: the delivery-time equation (2018)#

Assumptions. The first post, by Devansh Gupta, starts before any order exists:

  • Traffic. A customer opening the app sees a listing of 300 to 500 restaurants. To build it, Swiggy considers thousands more and must decide for each one whether to show it and what delivery time to promise.
  • Latency. The listing has to render in under half a second, so every per-restaurant computation must be tiny.
  • Consistency. The promise is a prediction, not a fact. It can be wrong, but it must be wrong in a predictable, small way.
  • Maintenance. The inputs (restaurant behaviour, rider positions, traffic) change all the time, so every estimate needs a fresh data feed.

The equation. The post breaks the delivery time into legs:

Delivery Time = max(Assignment Delay + First Mile, Prep Time) + Last Mile
  • Assignment delay is the time between placing the order and a DE accepting it.
  • First mile (FM) is the DE's ride from wherever they are to the restaurant.
  • Prep time is how long the kitchen takes to prepare and pack the food.
  • Last mile (LM) is the ride from the restaurant to the customer.

The max term reflects a simple physical fact. Food can leave only when both the food and the rider are at the restaurant. If the rider arrives early, they wait. If the food is ready early, it waits and cools.

Why each leg is hard.

  • Last mile. Swiggy chose not to rely on Google Maps for this. It was too slow for thousands of calls per listing, too costly at that volume, not aware of two-wheeler routes, and blind to the "last last mile". That final stretch from the gate to the door can add 5 to 10 minutes in big apartment complexes. The estimate is built from historical trips plus real-time rider movement.
  • Prep time. It depends on the item type (a pizza takes longer than a scoop of ice cream), how many items are in the order, and how loaded the kitchen is right now. The estimate is also used to time the rider's arrival, so an error here causes either rider waiting or cold food.
  • Assignment delay. It depends on how many free DEs are nearby, which depends on the time of day. The 8 to 10 PM dinner peak behaves very differently from the 4 to 6 PM lull. To estimate it, the system has to track every DE's state in real time.

The serviceability dilemma. Suppose one DE is free in an area and ten customers open the app. Showing all ten customers the restaurant risks ten orders with one rider: nine will be late. Hiding it from most of them loses demand that might have been served by a rider freeing up soon. The decision of whom to show, which the post calls serviceability, is a bet on near-future supply.

Goldilocks and the buffer. The post also argues against promising the average. If the promise is the mean delivery time, about half of customers get their food later than promised. The target is a "Goldilocks" value: not so long that customers leave, not so short that many orders are late. In practice that is a prediction plus a buffer chosen per context.

Overlooked constraints.

  • The promise changes behaviour. A shorter promise attracts more orders, which loads kitchens and riders, which makes the promise wrong. Any estimate feeds back into the system it predicts.
  • Errors are not symmetric. Early arrival is mildly pleasant; late arrival is a complaint, a cancellation or a refund. The buffer exists because the cost function is lopsided.
  • The equation hides correlation. A busy kitchen at dinner time usually coincides with traffic and rider scarcity. Leg errors add up rather than cancel.

What Swiggy sacrificed. Some conversion. A buffered promise is longer than the average, so some customers who would have been happy choose another restaurant or app. Swiggy also took on the cost of building its own distance and prediction systems instead of buying them.

Deep Dive: why the mean is the wrong promiseShow

Distribution shape (handbook's illustration). Delivery times are right-skewed. Most orders cluster near the typical time, but a long tail comes from rain, traffic jams and slow kitchens. Suppose a restaurant's deliveries have a median of 30 minutes, a mean of 32 minutes because of the tail, and a 90th percentile of 40 minutes.

  • Promise 32 minutes (the mean): roughly 45 percent of orders are late.
  • Promise 36 minutes: perhaps 20 percent are late, and the listing shows 4 more minutes.
  • Promise 40 minutes: about 10 percent are late, but the restaurant now looks slow next to a competitor showing 30.

Quantile thinking. Choosing a promise is choosing a quantile of the predicted distribution. The right quantile depends on the cost of lateness versus the cost of a long promise, which is why later posts (Lesson 12) measure "bi-directional compliance" and "egregious delay" rather than average error. A model trained with absolute error (L1 loss) predicts the median. A model trained with a quantile (pinball) loss predicts any chosen quantile. The buffer is the gap between them.

The max in the equation. If assignment plus first mile is 12 minutes and prep is 15 minutes, the rider waits 3 minutes and pickup happens at minute 15. If assignment slips to 8 minutes and first mile is 10, pickup moves to minute 18 and the food waits 3 minutes. The max term turns two independent errors into a single delay that depends on whichever leg is slower, so each leg must be estimated well, not just the total.

Lesson 2: The delivery challenge, part two: just-in-time assignment and batching (2019)#

Assumptions.

  • Traffic. Thousands of orders per city per hour at peak, with a fleet that is never large enough at dinner time.
  • Latency. Assignment runs every few minutes. Within each run, the solver has minutes, not hours, to decide.
  • Consistency. A DE must never be assigned two conflicting trips. Orders can wait a little; riders cannot be in two places.
  • Maintenance. The rules depend on many predictions (prep time, first mile, when a busy DE gets free), each maintained by a different team.

Closest is not best. The obvious rule is to assign each new order to the nearest free DE. It is locally good and globally bad. The nearest DE for this order may be the only DE near another restaurant whose order arrives a minute later. Good assignment looks at all pending orders and all DEs together.

Just-in-time (JIT) assignment. If the kitchen needs 20 minutes and the DE is 5 minutes away, assigning now makes the DE wait 15 minutes at the restaurant. A naive fix delays assignment by prep time minus average first-mile time. The better design earmarks a DE for the order early, but dispatches them just in time. While the order waits, the system can still swap: if DE A was earmarked for order O1 and DE B for O2, and a better pairing appears, they can be exchanged before anyone moves. The risks are real. A DE may reject the order after the delay, leaving less time to find another. Overestimated prep makes the DE arrive late, so the food cools. An underestimated first mile has the same effect.

Next-order assignment. A DE who will finish a delivery in the next X minutes, close to a restaurant with an upcoming order, is often a better candidate than a free DE far away. Including these "soon-free" DEs is implicitly JIT: the DE becomes available just as the food is ready. It depends on predicting when the current delivery ends, which is another model.

Batching. Giving one DE two or more orders that share a route is the single biggest lever on capacity. If every order could be batched in pairs, the fleet would effectively double. Orders are batchable when they are placed within a few minutes of each other, from the same or nearby restaurants, to nearby customers. The problem is a vehicle routing problem (VRP) with many drivers, pickups, drops and time windows. It is NP-hard: the time to solve it exactly grows exponentially with the number of orders.

Batching trade-offs.

  • Window size. Waiting longer to collect batchable orders finds more batches, but the first order in the batch waits. The best window varies by time of day and by area.
  • Promises. Swiggy raises the promised time only for orders likely to be batched, so customers are not surprised by the detour.
  • Heuristics. The solver prunes possibilities with rules (distance limits, restaurant clusters, time compatibility) because it has only minutes.

Overlooked constraints.

  • Predictions are inputs to optimisation. JIT only works if prep and first-mile predictions are good. A biased prep model silently turns JIT into cold food or idle riders.
  • Rejection is a state. A DE can say no. The assignment engine must keep enough slack to recover from a late rejection.
  • Customers see the detour. A batched order takes longer than a direct one. Without adjusting the promise, batching trades efficiency for broken promises.

What Swiggy sacrificed. Simplicity and some per-order speed. JIT and batching add waiting and detours for individual orders in exchange for fleet-wide efficiency. Swiggy accepted a heuristic, good-enough solution in place of an optimal one, because an optimal answer that arrives after the food is ready is useless.

Deep Dive: why batching is NP-hard and how heuristics copeShow

Counting the possibilities (handbook's illustration). With n pending orders and m DEs, a full solution groups orders into batches, orders the stops in each batch, and assigns batches to DEs. Even ignoring DEs, the number of ways to partition 20 orders into groups is the 20th Bell number, about 5 × 10^13. Multiply by stop orders and DE choices and exhaustive search is impossible in minutes.

Classic heuristics.

  • Construction. Start from single-order batches. Repeatedly merge the pair with the largest saving (distance saved versus separate trips), as in the Clarke-Wright savings algorithm (Clarke and Wright, 1964), while respecting time windows.
  • Insertion. For each new order, try inserting its pickup and drop into every existing route and keep the cheapest feasible position.
  • Local search and metaheuristics. Swap orders between routes, reverse segments (2-opt), or use simulated annealing or tabu search to escape local minima. Lesson 10 shows Swiggy's Instamart variant.

Pruning. Most order pairs are not batchable: different neighbourhoods, or placed 15 minutes apart. Filtering by restaurant cluster, drop distance and time compatibility reduces the candidate pairs from n squared to a small multiple of n. The solver then spends its time on plausible batches.

Saving per order. If a direct trip has a 1.5 km first mile and a 3 km last mile, two batched orders from the same restaurant share the first mile and part of the last mile. The fleet may save 30 to 40 percent of kilometres for those orders, at the cost of a few minutes for the second drop.

Lesson 3: Logistic zones for assignment: splitting a city with embeddings#

Assumptions. Ritwik Moghe's post describes a scaling problem inside the assignment algorithm itself:

  • Traffic. Orders per city grow quickly. The assignment problem is solved per city at short intervals.
  • Latency. Each run must finish before the next interval, or orders pile up and DEs idle.
  • Consistency. No DE may be assigned two batches in the same instant.
  • Maintenance. The split must adapt as cities grow, without hand-drawn boundaries.

The problem. Assignment is formulated as an integer linear program (ILP) over batches and DEs: a binary variable for each candidate (batch, DE) pair, with constraints that each batch gets at most one DE and each DE at most one batch. The solver's run time grows with the number of orders, and each candidate edge needs machine-learning features, fetched from Swiggy's Data Science Platform (DSP). In a fast-growing city the whole solve becomes too slow.

Zones as parallelism. The natural fix is to split the city into zones and solve each zone separately, in parallel. The danger is the boundary. A DE near the edge is a candidate for batches in two zones. If both zone solvers pick that DE, the first to commit wins and the other zone's batch waits for the next run. That adds delay and cost.

Requirements.

  • Minimise cross-zone conflicts.
  • Pick the number of clusters automatically, based on the run time each cluster would need.

Learning the zones.

  • The city is divided into geohash-7 cells, about 150 m by 150 m.
  • Historical assignment data gives "sentences": pairs of the restaurant's geohash and a candidate DE's geohash. Cells that often appear together in candidate edges belong in the same zone.
  • Word2Vec and FastText embeddings were trained on these sentences. FastText won because it learns from character n-grams. Geohashes are hierarchical strings, so a prefix like 'gbsuv' is shared by all its child cells such as 'gbsuv1'. With a minimum n-gram length of 5, FastText captures that spatial hierarchy for free.
  • Hierarchical clustering on the embeddings gives a tree. When a city's run time grows, the system moves one level down the tree to get more, smaller clusters.

The metric. The quality measure is the percentage of "at-risk" edges: candidate pairs where a DE is a candidate for batches in more than one cluster. FastText clusters had fewer at-risk edges than Word2Vec clusters. In simulation, zoned assignment ran much faster with minimal business impact. At the time of the post, production rollout was still in progress.

Overlooked constraints.

  • Partitioning a graph, not a map. The right zones follow where riders actually travel, not administrative lines. A river or a highway can split neighbours; a flyover can join distant cells.
  • Feature fetches dominate. The solver is not the only cost. Each candidate edge needs ML features, so fewer edges per zone also means fewer remote calls.
  • Clusters drift. New restaurants and new apartment complexes change travel patterns. The embedding must be retrained, and zone changes must not disrupt live operations.

What Swiggy sacrificed. Global optimality. A solution per zone can never use a DE across a boundary even when that would be best. Swiggy accepted a small loss in assignment quality for run times that fit the interval.

Deep Dive: the assignment ILP and why splitting it helpsShow

Formulation (handbook's illustration). Let x(b, d) be 1 if batch b goes to DE d. The objective minimises total cost, such as first-mile distance plus lateness penalties, over all candidate pairs. The constraints are: for each batch, the sum over d of x(b, d) is at most 1; for each DE, the sum over b of x(b, d) is at most 1. This is an assignment problem. In its pure form the Hungarian algorithm solves it in polynomial time. Business constraints such as batching, fairness and time windows make it a general ILP that a solver like Gurobi or OR-Tools handles with branch and bound.

Why size matters. With 2,000 batches and 3,000 DEs in a city, a dense formulation has 6 million variables. Pruning to DEs within a few kilometres might leave 50 candidates per batch, or 100,000 variables. Split into 10 zones, each solver handles about 10,000 variables, and the zones run in parallel. Solver time grows faster than linearly in problem size, so ten small problems finish far sooner than one big one.

The cost of boundaries. If 5 percent of edges are at risk and half of those cause a conflict in a run, about 2.5 percent of batches may be delayed by one interval. Better clustering cuts that fraction, which is why the post measures at-risk edges rather than cluster size alone.

Family 2: Serviceability, distance and geo

The next five posts are about one question that Swiggy must answer millions of times a minute: "Can we deliver from this restaurant to this customer, and how fast?" Swiggy calls the answer serviceability. It decides what you see on the home screen before you have tapped anything. These posts are a rare public look at a read path where the expensive part is maps and fleet capacity, not the database.

Lesson 4: What serviceability actually means (2020)#

Assumptions.

  • Traffic: about 100,000 listing requests a minute at the time of the post, each with 2,000 to 2,500 nearby restaurants or stores, and more checks on the menu and cart pages.
  • Latency: the whole check for 2,000+ outlets must fit in under 100 ms, a tenth of a second, so the listing page still feels instant.
  • Consistency: the answer can be slightly stale. A restaurant shown as deliverable a few seconds after the fleet tipped into stress is fine. A restaurant shown as deliverable that then takes 90 minutes is not.
  • Maintenance: every input (geo boundaries, maps, fleet state, ETA models, surge rules) is owned by a different team and changes at its own speed.

Most people think delivery systems start when you press "Place order". The post explains why that is wrong. An order has two phases. In the pre-order phase the customer browses, picks a restaurant and checks out. In the post-order phase the order is cooked, a delivery executive (DE, Swiggy's term for a rider) travels the first mile to the restaurant, picks up the food, and travels the last mile to the customer. If the pre-order phase shows a restaurant that cannot actually be served well, the post-order phase is doomed before it starts. So the delivery system has to be consulted the moment the app opens.

The post breaks serviceability into six steps:

  1. Geo-filtering. Reduce the global set of outlets to the ones near the customer. The naive way is radial filtering: draw a circle of radius X around the customer and keep everything inside. The flaw is that a circle has no direction. A restaurant 3 km away across a river with one bridge is not the same as one 3 km away along a main road. Swiggy uses directional filtering instead. It finds which customer cluster (a hand-drawn polygon) contains the customer with a point-in-polygon test. Then it reads the restaurant clusters that ops has connected to that customer cluster. Boundaries become a business tool: ops can shape them around rivers, rail lines and traffic patterns.
  2. Road distance. Straight-line distance ("as the crow flies") underestimates the trip. Swiggy needs the actual route length. It uses OpenStreetMap (OSM) for most pairs and Google Directions for some. On the OSM graph it runs a bidirectional A* search: two searches start at the source and the destination and meet in the middle, guided by a heuristic toward the goal. That is still expensive, and at about 2,000 pairs per listing and 100,000 listings a minute the system needs roughly 200 million distances a minute.
  3. Fleet stress. Riders cannot be summoned in minutes, but orders can arrive in minutes. Each zone sits at one of several discrete stress levels. The level moves based on the ratio of orders to available DEs, how fast demand is growing, logouts, the length of trips busy riders are on, and outside events such as rain and festivals. The stress system notifies serviceability and other systems when a level changes.
  4. Delivery-time prediction. The promise shown upfront must match reality. Lesson 1 showed the legs: assignment delay, first mile, prep time, wait time and last mile. This post adds the last last mile: the time from arriving at the building to handing over the food. Security gates, parking, finding the tower and waiting for a lift can add several minutes in a big apartment complex.
  5. Surge. A second way to cut demand under stress is a delivery fee that rises with the stress level. The surge factor depends on the stress level, the restaurant, the time of day and the last-mile distance. It can also be switched on for rain, festivals and special events.
  6. The decision. Each locality has limits on last-mile distance, delivery time and stress. If a pair breaks a limit, the outlet is hidden or shown as unavailable.

The key idea in step 3 is graceful degradation. Under stress, serviceability does not switch off. It first stops serving the orders that cost the most rider time: the ones with long last miles or long predicted delivery times. As the gap between demand and supply closes, the stress level falls and the limits relax. The stress system is described as a finite state machine (FSM): nodes are stress levels, edges are transitions triggered by ground conditions.

Overlooked constraints.

  • The read path drives the write path. Every listing check is a promise. If serviceability says yes too often, assignment and riders pay for it later, after the money is taken.
  • Fleet supply is inelastic in minutes. Cloud capacity scales in seconds; riders do not. So the system must throttle demand, not add supply. That makes it a load-shedding problem with a business face.
  • Distance is a computing problem, not just a data lookup. Route search on a city graph is CPU-heavy. At 200 million pairs a minute, distance becomes the biggest scaling problem in the stack.

What Swiggy sacrificed. Reach. Under stress, customers at the edge of a zone simply see fewer restaurants. Swiggy chose to lose some orders on purpose rather than accept orders it would deliver badly. It also accepted surge fees, which annoy customers, as a second demand lever.

Deep Dive: why a circle is the wrong delivery radius, and what point-in-polygon costsShow

Circles versus polygons (handbook's illustration). Suppose a city has a river with one bridge 2 km north of a customer. A restaurant 2.5 km away straight across the river is 6.5 km by road. A 3 km circle would include it; a polygon drawn by ops would not. Conversely, a restaurant 4 km away along a fast arterial road may be easy. A circle would exclude it, but a polygon connection could include it. Directional filtering moves this judgement out of code and into data that ops can edit.

Point-in-polygon. The classic test is ray casting: draw a ray from the point to infinity and count how many polygon edges it crosses. An odd count means inside. Each test costs O(n) in the number of polygon vertices. With 5,000 customer clusters of 50 vertices each, a brute-force scan is 250,000 edge checks per request. That is too slow at 100,000 requests a minute, which is why Lesson 5 adds a geohash index that shrinks candidates to a handful.

Why stress is discrete. A continuous stress number would make limits jitter every second, and the listing page would flicker. A few levels with hysteresis (for example, enter level 2 at 1.5 orders per DE, leave it only below 1.2) keep the system stable. This is the same reasoning a thermostat uses to avoid switching the heater on and off every few seconds.

Two levers, two costs. Hiding far restaurants cuts demand without charging anyone, but it loses revenue and choice. Surge keeps choice but makes some customers pay more. Using both lets Swiggy pick the gentler lever for small gaps and the stronger one for big gaps.

Lesson 5: Building the serviceability platform, part 1: geo-filtering and distance (2021)#

Assumptions.

  • Traffic: 100,000 visits a minute across home, listing, search, menu and checkout, times about 2,000 outlets: roughly 200 million evaluations a minute.
  • Latency: P99 under 200 ms for the full check. Distance needs under 1 ms per pair on average.
  • Consistency: distance can be cached for a long time. Roads change slowly, so a stale value is close enough.
  • Maintenance: the third-party maps contract has rules on caching and cost, so the cache must expire entries on a schedule.

This post by Sanket Payghan and Somsubhra Bairi turns the six steps into a system. It starts with an important statement: if serviceability is down, the whole pre-order flow is down. The home screen, listing, search, menu and checkout all call it. At checkout it may check several drop addresses for the same customer. That makes serviceability a tier-0 dependency, and every component below has a fallback.

Geo-filtering with a geohash index. A geohash turns a latitude and longitude into a short string. Each extra character narrows the cell. Nearby points usually share a prefix. Swiggy picks one geohash resolution and indexes each cluster polygon under every geohash cell it overlaps. A request then works like this:

  1. Convert the customer location to its geohash.
  2. Look up the few clusters indexed under that cell.
  3. Run point-in-polygon only on those few candidates to find the customer cluster.
  4. Fetch the connected pickup clusters from a local in-memory cache.
  5. Run point-in-polygon on the outlets against those pickup clusters.

The index is read-only for the request path and small enough to replicate on every node, so the service scales horizontally. If the customer is in no cluster, or the index or cache fails, the system falls back to radial filtering. That is the old circle: less precise, but always available.

Distance with a geohash-pair cache. Computing 200 million road distances a minute live is impossible on a sensible budget. The answer is a cache, but a cache needs a key. Raw latitude and longitude pairs make the key space effectively infinite: two customers in the same building have different coordinates. So keys are geohash pairs: the source cell and the destination cell.

The resolution choice is a direct trade-off:

  • Geohash level 8 cells are about 38 m by 19 m. They are accurate, but a city has hundreds of billions of possible pairs.
  • Geohash level 7 cells are about 153 m by 153 m. They are coarser, with far fewer pairs.

Swiggy caches only pairs that are actually queried often. Dense pairs use level 8 keys, sparse pairs use level 7 keys. Busy areas get precision where precision pays; quiet areas share coarser entries.

The cache has explicit capacity marks:

  • A TTL on each entry forces recomputation as roads and contract terms change.
  • A High Water Mark on memory triggers eviction.
  • A Stop Write mark above it rejects new keys entirely, so the cache never runs out of memory under a burst.

The cache is partitioned and replicated. The choice of provider per pair is also dynamic: Google Directions where accuracy matters most, OSM where cost matters most, decided from order-pattern signals.

The distance fallback chain has four steps:

  1. Cache hit: sub-millisecond.
  2. Cache miss: compute live with OSM bidirectional A*.
  3. OSM failure: use the Haversine distance (great-circle distance on a sphere), possibly scaled by a road factor.
  4. Whole primary cache cluster down: a secondary failover cluster takes over as primary.

Overlooked constraints.

  • Key design decides hit rate. The cache is only as good as its keys. A key too fine never repeats; a key too coarse gives wrong answers. Mixed resolution is the clever part.
  • Licence terms are a design input. Third-party map terms limit how long results may be stored. TTL is partly a legal control, not just a freshness control.
  • Memory pressure is a correctness risk. Without a Stop Write mark, a burst of new pairs during a sale could evict hot keys and send every request to live A*, which would collapse latency.

What Swiggy sacrificed. Precision at the cell edge. Two points 150 m apart in the same level-7 cell get the same distance. For a 3 km trip that error is small, but near a river or a flyover it can be large. Swiggy also accepted a less exact Haversine answer during outages rather than showing an empty home screen.

Deep Dive: sizing a geohash-pair distance cacheShow

Cell counts (handbook's illustration). Take a metro area of 1,500 square km. Level-7 cells are about 0.0234 square km, so there are about 64,000 cells. Level-8 cells are 32 times smaller, about 2 million cells. All level-8 pairs would be 4 × 10^12, about four trillion. Only pairs within, say, 7 km matter. That keeps roughly 154 square km around each cell, or about 210,000 level-8 cells, so about 4 × 10^11 pairs. That is hundreds of billions, which matches the post's concern.

What actually gets cached. Restaurants sit in perhaps 20,000 level-8 cells and active customers in perhaps 300,000. Most traffic comes from a fraction of those pairs. If 200 million pairs cover 90 percent of lookups, and each entry is about 40 bytes (two 8-byte keys, a 4-byte distance, a 4-byte expiry and overhead), the cache is about 8 GB per replica. A few Redis-class nodes can hold that, partitioned by key hash.

Why bidirectional A* helps. A one-directional search on a road graph expands a "ball" of nodes of radius r. Two searches that meet halfway expand two balls of radius r/2. In two dimensions the area grows with r², so the two half-balls are about half the work of one full ball. A good heuristic such as straight-line distance divided by maximum speed narrows the balls further. Even so, one query on a city graph can take several milliseconds, which is why the cache must absorb most traffic. Production routers also use preprocessing such as contraction hierarchies (Geisberger, Sanders, Schultes and Delling, 2008) to answer in well under a millisecond; GraphHopper supports this.

Haversine. For two points with latitudes φ1, φ2 and longitude difference Δλ, d = 2R · asin(sqrt(sin²(Δφ/2) + cos φ1 · cos φ2 · sin²(Δλ/2))), with R about 6,371 km. City road distance is typically 1.3 to 1.5 times the Haversine value. A fixed multiplier is a cheap and honest fallback.

Lesson 6: Building the serviceability platform, part 2: stress, predictions and the aggregator (2021)#

Assumptions.

  • Traffic: stress evaluated every minute for thousands of localities; predictions for every outlet-customer pair on every listing.
  • Latency: stress and predictions must be local reads at request time; nothing heavy can happen inline.
  • Consistency: stress state changes must reach all consumers, with retries so discrepancies stay small. A minute of lag is acceptable.
  • Maintenance: ML models are owned by the data science team and served from a separate Data Science Platform (DSP), which can fail independently.

Part 2 covers the remaining components and how they fit together.

The stress FSM as a distributed job. Each locality has its own state machine, evaluated every minute. Thousands of localities are too many for one node, so the job is spread across a cluster. The nodes agree among themselves on disjoint sets of localities, so each locality is owned by exactly one node. When a node joins or leaves, the cluster repartitions the localities. When a locality's state changes, the system sends the change through webhooks. Any system that cares (serviceability, assignment, pricing) registers a webhook, and delivery is retried so consumers do not drift apart.

Hyperlocal stress. Zone-level stress is too coarse in one way. A zone can be fine overall while one busy restaurant has no riders near it. So Swiggy also computes stress from the distribution of DEs around each pickup location. These jobs go through a stream to a pool of workers. The workers publish results to a pub/sub topic. The decision service subscribes and caches the latest values locally, so a request never waits on stress.

Predictions. The models predict each leg (assignment delay, first mile, prep, wait, last mile) plus the effect of batching. They are served from the DSP. Values that are stable within about a minute are cached. The post lists three failure modes: the DSP is down, the network to it is lost, or a model returns a wrong value. For all three, serviceability keeps light statistical fallback models in memory: moving averages by day, plus a linear regression per locality. They are recomputed daily from three weeks of history, saved, and loaded at startup. The primary models are deep learning and gradient-boosted trees; the fallbacks are good enough to keep promising sensible times.

The aggregator. The final decision needs many inputs. Some are internal (distance, stress, predictions). Some come from other teams (customer segment, favourite restaurants, item data). The aggregator models them as a dependency graph. Each job starts as soon as its own dependencies finish, and independent jobs run concurrently. Each component has its own fallback, so one slow input does not stall the whole response.

The last fallback: a second serviceability. Swiggy also built a lightweight, logically separate serviceability service with minimal dependencies. It is designed to take huge spikes with few resources. If the main platform fails, traffic shifts to it. It gives cruder answers, but the app keeps working.

Overlooked constraints.

  • Ownership must be exclusive. If two nodes evaluated the same locality, they could emit conflicting state changes. Disjoint assignment with rebalancing is the core of the stress cluster, and it is a leader-election and partitioning problem in disguise.
  • Push needs retries and idempotent consumers. Webhooks can fail or arrive twice. Consumers must treat a repeated "level 2" as harmless.
  • ML serving is a remote dependency like any other. Treating the model platform as fallible, with a local statistical twin, is a pattern many teams skip until their first model outage.

What Swiggy sacrificed. Simplicity and some accuracy. The system carries two sets of models, two serviceability services and a fallback for every step. That is more code to keep correct. During failures, customers see less accurate times. Swiggy decided that a slightly wrong promise beats no home screen.

Deep Dive: running a dependency graph inside a 200 ms budgetShow

The graph (handbook's illustration). Suppose the steps and their P99 times are: geo-filter 10 ms; customer segment 25 ms and favourites 30 ms, both independent; distance 20 ms after geo-filter; predictions 40 ms after distance; stress read 1 ms; decision 5 ms. Run in sequence, the total is 131 ms. Run as a graph, the critical path is geo-filter, distance, predictions, decision: 75 ms. The external calls run alongside and finish by 30 ms. The graph saves over 40 percent of latency without changing a single component.

Fallback timing. Each node gets its own timeout. If predictions do not answer in 40 ms, the in-memory fallback answers in 1 ms. The worst case for that path becomes 10 + 20 + 41 + 5 = 76 ms. Without the timeout, a DSP stall of 2 seconds would block every listing.

The fallback model. For locality L, hour h and day-of-week w, the base estimate is the average delivery time over the last three weeks at (L, h, w). A linear regression per locality then adjusts for distance: time ≈ a_L + b_L × distance. With three weeks of data at 1,000 orders a day per locality, each coefficient is fitted on tens of thousands of points, so it is stable. It cannot react to rain within the hour, but it is never absurd.

Partitioning localities. A simple way to get disjoint ownership is consistent hashing of locality IDs over the live node list. A membership service such as ZooKeeper or etcd, or a gossip protocol, tells each node who is alive. When a node leaves, only its share of localities moves. A node must stop evaluating a locality before another starts. A lease with an expiry, or a fencing token, prevents brief double ownership.

Lesson 7: Measuring map quality for two-wheelers with OSM (2025)#

Assumptions.

  • Traffic: an offline analytics workload: billions of GPS points over weeks against millions of OSM road segments in India.
  • Latency: batch; hours are fine. The online distance service in Lesson 5 is the consumer.
  • Consistency: quality scores are refreshed per time block; they describe the map over a window, not live.
  • Maintenance: OSM is crowdsourced. Errors appear and get fixed continuously, so measurement must be repeatable.

Distance is not only for serviceability. It also drives delivery fees, ETAs and how much DEs (now called delivery partners, DPs) are paid. This 2025 post by Abhinav G, Chandramouli K, Rahul Vippala and Jose Mathew explains why Swiggy leans on OSM rather than third-party maps, and how it measures where OSM can be trusted. Third-party map APIs are too slow for real-time use at this scale, too costly, and mostly priced for four-wheeler routes. Swiggy delivers mostly on two-wheelers, which can use lanes that cars cannot.

The problem is that OSM has errors: missing road segments, wrong one-way directions, phantom roads that do not exist, segments that should connect but do not, and wrong access rules. Swiggy needs to know where the map is good.

Four noisy distances. For each completed trip i there are four estimates:

  • OSM distance: the route the router computes on the OSM graph.
  • Third-party distance (TPD): from a commercial maps provider.
  • Trajectory distance (TD): Haversine summed between consecutive GPS pings from the rider's phone. GPS jitter makes it noisy.
  • Snapped distance (SD): the GPS trace matched onto OSM roads with GraphHopper's map-matching, then summed along the matched segments. This shows the road the rider most likely took.

None of these is ground truth. An earlier Swiggy paper (Gaurav et al., "Learning to Predict Two-Wheeler Travel Distance", ACM CODS-COMAD 2022) built a synthesized ground truth from all four, but it covers only part of the trips.

The OSM-APLS metric. APLS (Average Path Length Similarity) comes from research that extracts road maps from satellite images. It compares two road graphs by how similar their shortest-path lengths are. Swiggy adapts the idea. For each trip, the OSM route is checked against the snapped distance, but only when the snapped distance agrees closely with the trajectory distance. If GPS and the matched route agree, the matched route is trustworthy, so it is a fair judge of OSM. If they disagree, the trip is not used as evidence. Scores are rolled up to pairs of level-5 geohash cells (roughly 5 km by 5 km). The score lies between 0 and 1, and it is asymmetric: the road network from A to B can differ from B to A because of one-way streets. A pair scoring above a threshold is high-confidence.

Coverage and delta-coverage. Coverage is the share of OSM road segments in a level-5 cell that rider GPS traces actually touched in a time block. Delta-coverage is the share touched in this block but not in the previous one. A low delta means riders keep using the same roads, so the map's quality score is stable over time. A high delta means routes changed, perhaps because of construction or a new flyover, and the score needs a fresh look.

Computing coverage means joining billions of GPS points with millions of road segments. Swiggy does this in Spark using H3, Uber's hexagonal grid:

  1. Each OSM road (a linestring) is buffered into a polygon 5 m wide.
  2. The buffered polygons are filled with H3 cells at resolution 13, about 3.5 m per edge.
  3. GPS points are converted to the same resolution-13 cells and deduplicated across trips.
  4. Roads and points are joined on the H3 cell ID: an equality join, which Spark handles well, instead of a geometric join, which it does not.

Routing profiles. Swiggy uses GraphHopper, an open-source router, with its motorcycle profile. The car profile blocks some road types that bikes can use. There are three cost settings:

  • Shortest: cost is segment length.
  • Fastest: cost is estimated travel time from speed defaults and OSM max-speed tags.
  • Short-fastest: a weighted mix, cost = TimeFactor × time + DistanceFactor × distance. GraphHopper's defaults are TimeFactor 1 and DistanceFactor 0.07. That makes one hour of travel cost about the same as 14 km of distance.

On both mean absolute error against the synthesized ground truth and the OSM-APLS score, motorcycle short-fastest was the most accurate. It beat the third-party four-wheeler distance and the motorcycle fastest profile. Part 2 of the series, on machine learning to detect missing roads and connections, was announced but is not covered in the post itself.

Overlooked constraints.

  • Every reference is noisy. You cannot measure map quality against a perfect map, because none exists. Agreement between independent noisy sources is the substitute for truth.
  • Vehicle type changes the graph. A car-routing provider is wrong by design for bikes. Buying "the best map" does not help if it answers a different question.
  • Spatial joins do not scale naively. A geometric intersection of billions of points and millions of lines is hopeless. Turning geometry into discrete cell IDs makes it a normal hash join.

What Swiggy sacrificed. Coverage of the metric. Trips where GPS and the matched route disagree are thrown away, so areas with bad GPS (dense high-rises, tunnels) get no score. Choosing OSM over a commercial provider also means Swiggy must find and fix map errors itself. It gave up paying someone else for map quality in exchange for control and cost.

Deep Dive: the arithmetic of the H3 join and the short-fastest weightShow

Why resolution 13 (handbook's illustration). A resolution-13 H3 cell has an edge of about 3.5 m and an area of about 44 square metres. A road buffered to 5 m covers a strip about 10 m wide, so each 100 m of road fills roughly 20 to 30 cells. India has millions of OSM road segments; at an average of 150 m each, the road table is on the order of 10^8 to 10^9 cell rows. A month of pings at one ping every few seconds over millions of trips is billions of points, but after mapping to cells and deduplicating, far fewer distinct cells remain. Spark can hash-partition both sides on cell ID, so each executor joins only its slice.

Why a buffer. Consumer GPS error is often 5 to 10 m and worse near tall buildings. Without a buffer, a correct ping a few metres off the road centre line would never touch the road. Too wide a buffer would credit a parallel service road with the ride. A 5 m buffer is a deliberate middle.

The short-fastest weight. With TimeFactor 1 (per hour) and DistanceFactor 0.07 (per km), a 6 km route at 20 km/h costs 0.3 + 0.42 = 0.72. A 4 km route through slow lanes at 10 km/h costs 0.4 + 0.28 = 0.68, so the router prefers it slightly. Pure "fastest" would pick the 6 km route (0.3 versus 0.4). Pure "shortest" would always take the lanes. For bikes, where speed defaults on small roads are uncertain, mixing in distance guards against unrealistic speed guesses. That is one plausible reason it matched real rider paths best.

Original APLS. The APLS metric was introduced for the SpaceNet road-extraction challenge (Van Etten and co-authors, around 2018). It samples node pairs, compares shortest-path lengths in the ground-truth and proposal graphs, and penalises missing paths heavily. Swiggy's version replaces the perfect ground-truth graph with real trips that pass an agreement test.

Lesson 8: Geo queries at scale with Tile38 (2020)#

Assumptions.

  • Traffic: hundreds of millions of stored points; heavy read traffic from discovery, assignment and ops tooling.
  • Latency: 1 to 2 ms per query.
  • Consistency: availability matters more than consistency. A polygon update that takes a second to reach every replica is fine.
  • Maintenance: runs on Kubernetes, where pods and their local disks are temporary.

Tejeshwar Singh's post describes the general geo store behind many features. Some examples: "Is this customer in the same housing society as that one?", "Which DEs are in this area right now?", "Is this point inside an operating locality?", and "Which restaurants are near this customer?"

These reduce to four query types:

  • objects inside a polygon,
  • which polygon contains a point,
  • objects near a point,
  • shapes that intersect another shape.

The post classifies geo data by how it changes:

  • Type I: static shapes such as zones and housing societies.
  • Type II: static shapes that are switched on and off over time, such as "black zones" where delivery is paused, or areas with a special offer.
  • Type III: shapes that change all the time, such as live GPS traces.

Options considered. Each option was rejected for a concrete reason:

  • PostGIS on PostgreSQL is the standard answer, but the team had a bad experience with Postgres vacuum (the background clean-up of dead row versions) under heavy updates.
  • Google S2 and Uber H3 are libraries, not databases. Swiggy would have had to build persistence and high availability. S2's Go port was also incomplete at the time.
  • Tile38 was chosen. It is an open-source in-memory geo database that speaks the Redis protocol. It has persistence, replication and built-in geofencing: it can notify you when an object enters or leaves an area.

Tile38 persists writes to an append-only file (AOF) and replays it on startup. That makes restarts slow, which Swiggy accepted. A benchmark on a single core handled 100 million points and a few million 20-vertex polygons. Swiggy runs it as a sidecar, a container next to each application instance, so queries are local calls.

High availability: the interesting choice. Tile38's built-in replication is leader-follower, and a failed leader needs something to promote a follower. The team looked at:

  • Redis Sentinel style monitoring: extra machines, and the monitor itself needs to be highly available.
  • Ringpop, Uber's consistent-hashing membership library: unmaintained and chatty on the network.
  • Hazelcast: one more distributed system to run.
  • etcd/Raft: strongly consistent (CP), which is the wrong side of the trade-off for this use.

The chosen design is masterless clones fed by Kafka. A pre-command hook on each write publishes the command to a Kafka topic. Every Tile38 clone consumes the topic and applies every write. There is no leader to fail. The cost is that writes take slightly longer and replicas are only eventually consistent.

Durability on temporary disks. Kubernetes pods lose local disks when they move. So:

  1. Each clone uploads its AOF to S3 every 30 minutes.
  2. A pre-startup hook downloads the latest AOF before a new clone starts.
  3. The new clone replays the AOF, then reads Kafka from the earliest retained offset.
  4. Kafka retention is longer than 30 minutes, so no write between the snapshot and now is lost.

Replaying an old write that is already in the snapshot is harmless because geo writes such as "SET object to this point" are idempotent.

Overlooked constraints.

  • Retention must exceed the snapshot interval. If Kafka keeps writes for less than 30 minutes, a restart loses the gap silently. This one setting carries the whole durability story.
  • Startup time becomes availability. Slow AOF replay means a node is useless for minutes after a restart. With sidecars, that is one app instance unable to serve, so the rollout and autoscaling must allow for it.
  • Idempotent writes are what make replay safe. An "increment" command replayed twice would corrupt data. Geo SET commands that overwrite are safe.

What Swiggy sacrificed. Strong consistency and write latency. Two clones can briefly disagree on whether a black zone is active. Each write takes an extra Kafka hop. It also gave up a managed product: Swiggy runs Kafka, Tile38, S3 snapshots and the hooks itself.

Deep Dive: Kafka as a replication log, and the memory mathShow

The log is the database. This design treats Kafka as the source of truth and every Tile38 instance as a derived view. It is the same idea as state machine replication: if every replica starts from the same state and applies the same ordered commands, they end in the same state. One partition per topic gives a single total order. With several partitions, writes to the same object must use the same key so their order is preserved.

Memory sizing (handbook's illustration). A point object with an ID of about 20 bytes, two 8-byte coordinates and index overhead might take about 100 bytes in memory. 100 million points is then about 10 GB. A 20-vertex polygon is 320 bytes of coordinates plus index nodes, say 500 bytes; 3 million polygons is about 1.5 GB. That fits comfortably in a 16 GB container, but it rules out running a full copy next to every small service. That is why sidecars suit read-heavy services with real memory headroom.

Replay time. If the AOF has 200 million commands and replay runs at 1 million commands a second, a cold start takes over 3 minutes, plus the Kafka catch-up. Compacting the AOF (rewriting it to just the current state) shortens this. Kubernetes readiness probes must stay false until replay ends, or traffic will hit an empty index.

Why not CP. With Raft, a write needs a majority acknowledgement, and a minority partition cannot serve writes. For a geo store whose writes are mostly ops edits and DE positions that change every few seconds, refusing writes is worse than briefly stale reads. The masterless design accepts any write, as long as Kafka is up. Its single point of dependency is Kafka, which Swiggy already runs with replication. Lesson 16 shows what happens when that dependency breaks.

Family 3: The logistics platform

Serviceability decides what can be promised. The next three posts are about the machinery that keeps the promise once money changes hands: the platform that models a delivery, the optimiser for grocery orders, and the system that moves riders to where demand is about to be.

Lesson 9: Re-architecting the logistics platform (2021)#

Assumptions.

  • Traffic: every order in every business line goes through this platform, so its write path is the busiest in logistics.
  • Latency: state changes (assigned, picked up, delivered) must reach the rider app, customer app and restaurant within seconds.
  • Consistency: a task's state must be exact. A rider cannot be both "at restaurant" and "delivered".
  • Maintenance: new business lines (groceries, pick-up-and-drop, scheduled orders) keep arriving, and each must not need a new fork.

Ravi Singh's post is a candid account of a monolith that reached its limits. The Delivery service held about a third of Swiggy's business logic. When new businesses needed delivery, teams forked it instead of extending it. That is Conway's law in action: the system's structure followed the team structure. The forks had no plan to be retired. Test coverage was low, so changes were risky. Its MySQL and Redis stores had been scaled vertically as far as they could go. Most importantly, the model was food-only and two-legged: go to the restaurant, then go to the customer. Anything else, such as a stop at a shop or a pickup from a customer, did not fit.

From July 2018, when Swiggy Stores and the Genie pick-up-and-drop service launched, the vision was a multi-tenant, multi-service-line platform. Multi-tenant here means many business lines share the platform with logical isolation: their data and configuration are separated, not their machines.

The new domain model. The redesign replaced "order with two legs" with four general concepts:

  • Task: the smallest unbreakable unit of work. Examples are PickUp, Drop, or "click a photo of the item".
  • Job: the sequence of tasks a client (a business line) wants done. A food order is a job of two tasks; a Genie errand might have more.
  • Job leg: the part of a job that one DE does.
  • Trip: the sequence of tasks one DE does, possibly from several jobs.

This split between "what the client wants" (job) and "what one rider does" (trip) unlocked three capabilities:

  • Merging: two jobs can share one trip, which is batching in the general form.
  • Fission: one job can be split into legs done by different DEs, for example hub-and-spoke delivery through a transfer point.
  • Sub-states: a task can have its own internal states, such as shopping, confirming a substitute with the customer, and paying at the shop.

Event-driven, three tiers. The platform is built from event-driven services in three tiers:

  • Utility services provide generic capabilities.
  • Platform services implement the domain model.
  • Service layer adapts each business line.

With this in place Swiggy could add single-task jobs (for example, moving a DE to a busy area before demand arrives), Genie, Instamart, round trips, scheduled and subscription deliveries, and multi-stop routes, without forking.

Overlooked constraints.

  • Forks are debt with interest. Each fork copies bugs and needs its own fixes. Without a retirement plan, the cost of change grows with every business line.
  • The model is the platform. Most of the gain came not from new technology but from choosing the right nouns. A task-level model can describe businesses that did not exist when it was designed.
  • Migration while running. Moving live delivery traffic off a monolith that owns a third of the logic needs dual-running, shadow traffic and gradual cut-over, or one bad deploy stops every order.

What Swiggy sacrificed. Short-term speed. A general model is harder to understand than "restaurant, then customer", and each business line now pays a translation cost into tasks and jobs. Event-driven tiers also bring eventual consistency between services and harder debugging across many hops.

Deep Dive: modelling deliveries as tasks, and checking a multi-stop tripShow

A Genie errand as tasks (handbook's illustration). "Pick up a parcel from home, buy medicine at a pharmacy, drop both at a parent's house" becomes one job with tasks: PickUp(home), Shop(pharmacy, sub-states: shopping, confirming, paying), Drop(parent). If two Genie jobs start near each other, the trip can interleave them: PickUp A, PickUp B, Drop A, Drop B. The platform must check precedence: every Drop must come after its PickUp in the same trip.

Precedence check. For a trip of n tasks, keep a set of picked-up job IDs while walking the sequence. A Drop whose job is not in the set is invalid. That is O(n), cheap enough to run on every proposed merge. Capacity checks work the same way: add each pickup's size, subtract on drop, and fail if the running total exceeds the bag limit.

Task state machine. A Drop task might move through CREATED, ASSIGNED, ARRIVED, DELIVERED, plus FAILED and CANCELLED. Each transition is an event. Storing the transitions as an append-only log per task gives a full audit trail. This is what support agents need when a customer says "my order never arrived". Event sourcing ideas apply here without making the whole platform event-sourced.

Why logical isolation. Separate deployments per business line would multiply cost and bring back the fork problem. Shared deployments with a tenant key on every row, per-tenant configuration and per-tenant rate limits give most of the isolation at a fraction of the cost. The risk is a noisy neighbour: one business line's spike affecting another. Per-tenant quotas at the API layer are the usual guard.

Lesson 10: Batching and assignment for Instamart (2022)#

Assumptions.

  • Traffic: at the time of the post, over 200,000 orders a day, over 150,000 DEs on the platform, and over 100 dark stores.
  • Latency: the optimiser runs on a rolling cron, and each stage must finish in under a minute.
  • Consistency: a DE must be assigned to one batch at a time, and a batch to one DE.
  • Maintenance: grocery promises are short (often minutes), so tuning must be fast and safe.

Instamart is Swiggy's quick-commerce grocery service. Orders are packed at dark stores: warehouses closed to the public. Siddhartha Paul's two-part series explains how orders become batches and batches get riders.

The problem. In operations-research terms it is a multi-depot dynamic pickup and delivery problem with time windows (MDPDPTW). Multi-depot means many stores. Dynamic means orders keep arriving while you plan. Pickup and delivery with time windows means each order has an earliest and latest pickup time and an earliest and latest delivery time. A natural shortcut is to cluster stores and solve each cluster alone, but riders near two stores belong to both clusters, so clustering gives poor answers.

Two stages on a rolling horizon. Each cron run solves:

  1. Last-mile batching and routing. Group orders from a store into batches and order the drops. The solver uses a construction heuristic plus a metaheuristic for the dynamic pickup-and-delivery problem, or a greedy method when time is short.
  2. First-mile just-in-time (JIT) assignment. Assign a DE to each batch so the DE arrives as the batch is packed.

The cron-length dilemma. A longer interval between runs collects more orders, so batches are better. But orders wait longer to be assigned, so order-to-assignment time (O2A) goes up. The fix is clever. Once a DE has set off for the store, the route up to the store is frozen, but the solver can still insert new orders into that DE's batch until pickup. The batch keeps improving without delaying assignment.

Why batching pays. The post reports that batching halved the per-order first-mile distance, from about 1 km to about 0.5 km. One trip to the store now serves two orders.

Constraints the solver respects.

  • Weight and volumetric weight (bulky but light items like crisps).
  • A capacity of k orders per batch.
  • A constant service time per stop.
  • LIFO for perishables: the last item loaded comes out first, so ice cream is loaded last and delivered first.
  • Time windows: earliest and latest pickup and delivery times.
  • Dynamic state: DE positions and order statuses change between runs.

Part 2: making picking, packing and assignment run in parallel. In a dark store, staff pick items from shelves while the system batches orders and assigns DEs. The aim is to overlap these steps, so order-to-pack time is roughly O2A plus first mile rather than a sum of everything.

There are two kinds of JIT:

  • External JIT: do not assign too early. Hold the order until a slot or a promise deadline makes it urgent. The post's example: with a 15-minute promise, 3 minutes of first mile and 2 minutes of O2A, the order can be held for up to 10 minutes while better batches form.
  • Internal JIT: a multi-objective assignment. Each DE gets at most one batch and each batch at most one DE. The solver weighs "assign now" against "wait for the next run". Its objective combines cost per delivery (CPD) and a customer-experience penalty that grows with delay.

Overlooked constraints.

  • Waiting is a decision variable. Most dispatch systems assign as soon as possible. Treating "not yet" as a valid answer is what makes batching work.
  • Physical loading order matters. LIFO for perishables comes from the rider's bag, not from the software. Constraints like this only appear by talking to the people on the ground.
  • The solver has a hard deadline. A heuristic that finds a good answer in 30 seconds beats an exact one that needs 3 minutes, because the world has changed by then.

What Swiggy sacrificed. Optimality and simplicity. Heuristics give no guarantee of the best plan. Holding orders means some customers wait a little longer for assignment so the fleet is used better. The frozen-route-plus-insert trick adds complex state to every in-flight batch.

Deep Dive: insertion heuristics, hold time and the cost of a bigger batchShow

Cheapest insertion (handbook's illustration). A batch route is store, then drops d1, d2, d3. For a new order with drop x, try placing x between every adjacent pair and compute the extra distance: dist(a, x) + dist(x, b) minus dist(a, b). Pick the cheapest position that keeps every time window and the LIFO rule. With k drops that is k + 1 positions, so O(k) per order. Metaheuristics such as large neighbourhood search then remove a few orders and reinsert them in better places, again and again, until time runs out.

Hold-time formula. Latest assign time = promise − expected first mile − expected O2A − safety margin. For a 15-minute promise, 3 minutes of first mile, 2 minutes of O2A and 1 minute of margin, hold up to 9 minutes. The margin covers prediction error. If first-mile predictions have a standard deviation of 1.5 minutes, a one-sided 75 percent buffer is about 1 minute. A 95 percent buffer would be about 2.5 minutes, which leaves less hold time and smaller batches.

When batching stops paying. If two drops are 400 m apart, the second order adds a few minutes and saves a full first mile. If they are 3 km apart in opposite directions, the second customer waits much longer. The solver's customer-experience penalty must grow faster than linearly with delay, for example quadratically, so it does not trade one very late order for two slightly cheaper ones.

Literature. The pickup and delivery problem with time windows has a long operations-research history. Dynamic versions are usually solved with rolling-horizon re-optimisation, as here, because exact methods cannot keep up with arrivals.

Lesson 11: Supply shaping: moving riders before demand arrives#

Assumptions.

  • Traffic: a decision every couple of minutes for every zone in a city.
  • Latency: recommendations must look about 15 minutes ahead, which is roughly how long it takes a DE to move between zones.
  • Consistency: recommendations are advice. A DE can ignore one, and the system must still be safe.
  • Maintenance: models are retrained often; the optimiser first ran in shadow mode, producing recommendations that were logged but not sent.

Ambuj Tiwari and co-authors tackle a problem every delivery platform has. Zones are operational clusters with their own riders. Orders that cross zones leave DEs stranded far from home, where there may be no orders. Some zones then have too many idle riders and others too few. Reacting after a zone tips into stress is too late. The system must recommend moves about 15 minutes ahead.

The work has four parts.

1. Superzones. Zones are grouped into superzones that the optimiser uses to move riders between neighbouring zones. Nothing changes on the ground; the grouping exists only inside the optimiser.

2. Defining demand and supply. This sounds obvious but is the heart of the post.

  • Definition 1: demand is the number of batched orders.
  • Definition 2: demand also counts the backlog of batches that have not yet been assigned. At peak, this backlog correction was about 30 percent of demand, and its correlation with stress was about six times higher than Definition 1's.
  • Definition 3 was explored and parked.

Stress is defined as active orders divided by logged-in DEs. The post separates spillover (demand that flowed into a zone from a neighbour) from backlog. Supply counts DEs who are assigned, DEs with no current activity, and busy DEs who will be free within 15 minutes.

3. Forecasts. XGBoost models predict demand and supply per zone. They beat the earlier gradient-boosted trees and are refreshed every 2 minutes.

4. Optimisation. A constrained model, solved with Gurobi, decides how many DEs to move from zone i to zone j. Call that y(i, j). Constraints:

  • each DE goes to at most one zone;
  • deficit zones must end with a smaller deficit;
  • surplus zones meet their own demand before giving riders away;
  • busy DEs stay in their current zone.

Measuring success. Forecast error was 10 to 15 percent wMAPE (weighted mean absolute percentage error). Precision at identifying sink zones (needing riders) and source zones (with spare riders) was over 90 percent. Definition 2 gave about three times the precision of Definition 1. Recommendations were also checked for accuracy against what actually happened. One tuning trade-off: a recommended DE might be 4 to 6 km away from the deficit zone, which helps the zone but costs the rider a long empty ride.

Overlooked constraints.

  • The metric definition is the model. A cleverer forecaster would not have fixed Definition 1, because it measured the wrong thing. The six-times jump came from counting backlog.
  • People are not pieces. A recommendation sends a human on a ride that pays nothing until an order arrives. Distance limits, incentives and trust all decide whether it works.
  • Forecasts feed actions that change outcomes. If riders move, the deficit the model predicted shrinks, so judging the model on the outcome is tricky. Shadow mode gives a clean baseline first.

What Swiggy sacrificed. Rider freedom and some short-term cost. Riders are nudged to move without an order. Some recommendations will be wrong and waste fuel and time. Running in shadow mode first also delayed the benefit in exchange for measurement.

Deep Dive: the rebalancing model as a transportation problemShow

Formulation (handbook's illustration). Let s_i be zone i's forecast surplus (supply minus demand in 15 minutes) and let y(i, j) be the DEs moved from i to j, with travel cost c(i, j). Minimise the sum of c(i, j) × y(i, j) plus a penalty P times each zone's remaining deficit. Constraints: for a surplus zone, the sum over j of y(i, j) is at most s_i. For a deficit zone, the remaining deficit is at least −s_j minus the sum over i of y(i, j), and at least 0. Only pairs within the same superzone and under a distance limit get a variable. This is a classic transportation problem, which linear programming solves quickly. Integer values are natural because the constraint matrix is totally unimodular in the pure form.

Worked example. Zone A has surplus 6, zone B deficit 4, zone D deficit 3. Costs: A to B is 2 km, A to D is 5 km. With a high deficit penalty, the solver sends 4 to B and 2 to D, leaving D short by 1. If the distance limit is 4 km, the A to D move is not allowed, so D stays short by 3 and the system may raise surge there instead. That is how supply shaping and surge from Lesson 4 complement each other.

wMAPE. wMAPE = sum of |actual − forecast| divided by sum of actual. Unlike MAPE, a zone with 2 orders and a forecast of 4 does not count as a 100 percent error with equal weight to a busy zone. Busy zones dominate, which matches where riders matter most.

Uber parallel. Uber's dispatch and driver-positioning work faces the same problem with cars. Lesson 4 and the Uber page show how surge and positioning are two levers on one supply-demand gap.

Family 4: Predictions and forecasting

Every decision so far leans on a prediction: how long will this order take, and how many orders will this zone see? The next three posts show the models behind those numbers, and, just as important, how Swiggy measures whether a prediction is good enough to act on.

Lesson 12: The cart promise: a multi-output delivery-time model#

Assumptions.

  • Traffic: one prediction per cart view and checkout, across every city.
  • Latency: a few tens of milliseconds, inside the serviceability budget from Lesson 5.
  • Consistency: the promised time is shown to the customer and then reused by assignment, customer care and exception handling. It must be one number shared by all of them.
  • Maintenance: restaurants, cities and customer areas are added constantly, so the model must handle new entities.

The time shown at checkout is called the promised SLA (pSLA). Shubham Grover and co-authors explain why it matters beyond the customer's screen. Assignment uses it to decide urgency. Customer care uses it to judge whether an order is late. Exception management uses it to trigger action. A bad promise therefore causes bad decisions all the way down.

What drives delivery time. The post lists restaurant type, number of items, dish type (a biryani takes longer than a soft drink), DE availability and distance.

How to score a promise. Mean absolute error (MAE) alone is not enough, because customers feel lateness more than earliness. Swiggy uses three metrics:

  • MAE, the average size of the error;
  • BDC, the share of orders delivered within plus or minus X minutes of the promise;
  • ED (extreme delays), the share delivered more than Y minutes after the promise.

One model, many outputs. Instead of one model for the total, the model predicts each leg at once: O2A (order to assignment), FM (first mile), WT (wait at restaurant), LM (last mile) and O2R (order to reach, the total). It is a MIMO (multi-input, multi-output) deep learning model. Shared layers learn common patterns, then branches specialise per leg. The model learns that O2A + FM + WT + LM should equal O2R, so the parts and the whole stay consistent.

Why the legs are coupled. The post's example shows why predicting the legs together beats predicting them separately. Restaurant A's nearest free DE is 10 minutes away, so the system assigns within about 5 minutes and accepts a long first mile. Restaurant B has five DEs waiting outside, so assignment can wait until about minute 15 with almost no first mile. O2A and FM trade against each other. A model that predicts them separately would miss that their sum is what matters.

Entity embeddings. Restaurants, customer geohashes and cities are fed as learned embeddings: dense vectors that place similar entities near each other. A new restaurant in a busy area gets a sensible starting vector from its neighbours' patterns.

Features. Historical moving averages and near-real-time ones; the output of a separate prep-time model; restaurant stress; order size; item history; active DEs compared with orders; and last-mile speed patterns.

Results. Compared with the previous approach, training used about half the memory and about a fifth of the time. O2A error fell about 30 percent and O2R error about 5 percent. The stated next steps were a custom loss that penalises lateness more, and better handling of sparse groups.

Overlooked constraints.

  • A prediction becomes a contract. Once the promise is shown, other systems treat it as the deadline. A model tuned only for average accuracy can create systematic lateness alarms.
  • Legs interact through decisions. The assignment system reads the prediction and then acts, which changes O2A. The model must learn from data produced by its own past decisions.
  • Cold start is constant. New restaurants and areas appear daily. Embeddings help, but only with fallbacks to city or cuisine averages.

What Swiggy sacrificed. Interpretability. A shared deep network is harder to explain than separate simple models. When a promise is wrong, finding which input caused it takes more tooling. Swiggy accepted that cost for consistent legs and cheaper training.

Deep Dive: multi-task learning and why the sum constraint helpsShow

Multi-task loss (handbook's illustration). Let the model output o2a, fm, wt, lm and o2r. A simple joint loss is L = w1·|o2a − y_o2a| + w2·|fm − y_fm| + w3·|wt − y_wt| + w4·|lm − y_lm| + w5·|o2r − y_o2r| + λ·|o2a + fm + wt + lm − o2r|. The last term pushes the legs to add up to the total. With absolute error (L1), each head predicts the median rather than the mean, which is less sensitive to rare very late orders.

Why sharing helps. O2A and FM both depend on how many DEs are nearby. A shared layer learns that "DE density" signal once and both heads use it. In multi-task learning, related tasks act as regularisers for each other. Training one network instead of five also explains the memory and time savings.

BDC and ED in numbers. Suppose 1,000 orders, with X = 5 and Y = 10 minutes. If 720 arrive within 5 minutes of the promise, BDC is 72 percent. If 40 arrive more than 10 minutes late, ED is 4 percent. Two models with the same MAE can differ a lot on ED. One spreads small errors evenly; the other is usually right but sometimes very late. Customers remember the second.

Asymmetric loss. The planned custom loss would penalise lateness more. A pinball (quantile) loss at τ = 0.7 charges 0.7 per minute late and 0.3 per minute early. The model then learns the 70th percentile, which builds a buffer into the promise. This is the same idea as Lesson 1's "promise a percentile, not the mean".

Lesson 13: "Where is my order?": live ETA models (WIMOC)#

Assumptions.

  • Traffic: an ETA update every time a customer opens tracking, and customers open it many times per order.
  • Latency: each refresh must be fast, so models are small and features come from streams.
  • Consistency: ETAs should move only when reality moves. A number that jumps up and down without reason erodes trust.
  • Maintenance: four models, one per stage, each refreshed on a schedule.

Vaibhav Agarwal's two-part series covers the ETA on the tracking screen. Once an order is placed, the cart promise is the starting point, but the live ETA must update as the order moves through stages. There are four models, one per stage, built on top of the cart SLA:

  • OR (order to assignment): inputs include the count of DEs nearby and their distance, stress, rain and rider rejection rates.
  • FM (first mile): the DE's familiarity with the restaurant, vehicle type, location pings, current and global speed, and whether the restaurant has confirmed the order.
  • WT (wait time): restaurant stress, the restaurant's live order count, and how much prep time has passed.
  • LM (last mile): pings in a time window with outliers removed; current speed computed as Haversine distance summed over the window divided by time; remaining distance; distance covered so far; and the global speed. These features let the model notice a rider stuck at a notorious junction, such as Bengaluru's Silk Board, and adjust.

An example from the post. A 37-minute ETA dropped to 25 minutes after the order was assigned early. Live models catch good news as well as bad.

Measuring a moving number. Accuracy alone is not enough. Swiggy uses an MAE threshold plus a second metric: the percentage of orders with inaccurate bumps. A bump is a jump in the ETA. A bump that reflects a real change (rain, a late restaurant) is necessary and is not penalised. A bump that later reverses is inaccurate and is penalised.

Results. Gradient-boosted trees (GBT) with absolute-error loss gave 62 percent better accuracy and 27 percent fewer bumps than the old system. A neural network gave 15 percent better accuracy and 12 percent fewer bumps. The networks were small: four layers, Leaky ReLU activation, 50 epochs, Adam optimiser. Layer widths were 32, 32, 16, 16 for OR; 24, 24, 12, 12 for FM; 16 four times for WT; and 8 four times for LM. Better ETAs meant fewer customer-care contacts and fewer cancellations. Future ideas included RNN or LSTM sequence models over pings, graph neural networks over the road graph, and point-of-interest features.

Overlooked constraints.

  • Stability is a requirement. The first instinct is to chase accuracy, but customers punish flip-flopping more than small steady errors. The bump metric makes stability measurable.
  • GPS is noisy. Outlier removal and windowing come before any model. One bad ping can teleport a rider 500 m.
  • Stage boundaries depend on events. If the "picked up" event arrives late, the LM model starts late. Event latency becomes ETA error.

What Swiggy sacrificed. Model simplicity. Four models, each with its own features and refresh, are more to run than one. The team also picked GBT over the neural network, choosing the better-measured model over the newer technique.

Deep Dive: computing live speed and scoring bumpsShow

Live speed (handbook's illustration). Take the last 2 minutes of pings: 12 points at 10-second intervals. Remove points that imply more than 80 km/h between neighbours, since a two-wheeler in city traffic rarely does that. Sum the Haversine distance between the remaining consecutive points: say 700 m over 110 seconds, or about 23 km/h. If 2.8 km remain, a naive ETA is about 7.3 minutes. The model blends this with the global average speed for that road and hour, because a rider stopped at a light for 60 seconds would otherwise get a wildly pessimistic ETA.

Bump scoring. Record the ETA sequence for an order, for example 30, 30, 34, 31, 30, 30. The jump to 34 reversed within two refreshes, so it counts as an inaccurate bump. A sequence 30, 30, 36, 36, 37 after a rain alert would be a necessary bump if the final delivery time matches 36 or 37. The percentage of orders with at least one inaccurate bump is the metric.

Why absolute loss with trees. Delivery times have long right tails: a few orders take an hour. Squared loss lets those few dominate training. Absolute loss targets the median and ignores how extreme an outlier is, which helps both accuracy and stability.

Smoothing at serve time. A simple guard is to show a new ETA only if it differs from the last shown value by more than a threshold, say 2 minutes, or if it has persisted for two refreshes. This is hysteresis again, the same tool as the stress levels in Lesson 4.

Lesson 14: Hyperlocal forecasting at scale#

Assumptions.

  • Traffic: forecasts for thousands of zones, for several metrics, refreshed in batch and sometimes in real time.
  • Latency: batch runs must finish before the planning window; real-time serving goes through the DSP.
  • Consistency: a forecast is reproducible from versioned data and models.
  • Maintenance: many teams forecast different things, so the tooling must be shared and testable.

Varun Jampala and co-authors describe Swiggy's forecasting framework. Rider planning, store staffing and supply shaping all need forecasts per zone, per hour. Thousands of zones times several metrics means hundreds of thousands of time series.

Techniques that moved the error. The post reports gains for each:

  • Model tournament: for each series, backtest several models and pick the best. This gave 15 to 30 percent lower error than one model for all.
  • Ensembles: averaging the best few gave 10 to 20 percent more.
  • Event handling: festivals, cricket finals and sales distort history.
    • Pre-processing replaces past event days with forecasts, so they do not teach the model false patterns.
    • Post-processing applies an Event Impact Model to the residuals for upcoming events, giving 5 to 15 percent lower wMAPE.
  • Time reduction and time shift: reshape the problem (for example, forecast at a coarser grain and split back down, or shift series to align patterns). Time-shift gave 5 to 10 percent.

The candidate models range from classical ARIMA and ETS, through Prophet and DeepAR, to XGBoost with lag features, with moving averages as a baseline that every model must beat.

The pipeline. Dataset, then pre-processing, then training (with AutoML backtests and composite models), then post-processing, then deployment: either batch, or real-time on the Data Science Platform.

Design tenets. Modular, extensible, scalable (k metrics times up to 100,000 series), reusable, collaborative and testable.

The SDK. The framework copies scikit-learn estimator semantics, with fit and predict, but takes and returns Spark DataFrames. It logs runs in MLflow and runs in isolated Conda environments on Databricks clusters. Models compose with decorators: for example, a time-shift wrapper around a reduction wrapper around Prophet. An XGBoost forecaster builds its own lag features. One operational lesson: fewer, bigger workers beat many small ones, because the job shuffles less data between machines.

Overlooked constraints.

  • History lies around events. A model trained on last Diwali learns a spike that may not recur on the same date. Cleaning history is as important as choosing the model.
  • No single model wins everywhere. Busy central zones and new suburban zones behave differently. Per-series selection is the honest answer.
  • Cluster shape matters. Distributed training is often limited by network shuffle, not CPU. More machines can make it slower.

What Swiggy sacrificed. Simplicity of the forecasting stack. A tournament plus ensembles plus event models is much heavier than one global model. It also costs compute: every series is backtested with several models on every run.

Deep Dive: backtesting a tournament without fooling yourselfShow

Rolling-origin backtest (handbook's illustration). For a series with 90 days of hourly data, train on days 1 to 60 and forecast days 61 to 67. Then train on 1 to 67 and forecast 68 to 74, and so on. Average wMAPE across the folds. Never shuffle time series data into random folds: the model would see the future.

Tournament maths. With 5 candidate models, 3 folds and 50,000 series, that is 750,000 model fits per run. At 0.5 seconds each on one core, about 104 core-hours, or about an hour on 100 cores. That is why the SDK runs on Spark and why worker sizing matters.

Selection bias. If you pick the best of 5 models on the same folds you report, the reported error is optimistic. A held-out final fold, never used for selection, gives an honest estimate. The gain from a tournament is real but smaller than the in-sample numbers suggest.

Event pre-processing. Suppose a zone normally gets 400 orders on a Sunday evening and 900 on a cricket final day. If you leave 900 in the training data, a seasonal model will expect extra demand the same week next year. Replacing it with a forecast of about 400 removes the false signal. The Event Impact Model then learns separately that "cricket final" means about +125 percent and applies it only when a final is scheduled.

Related handbook pages. The stream and batch processing page covers how such pipelines are scheduled, and the time-series databases page covers how the inputs are stored.

Family 5: Data platform and reliability

Models need data, and data needs pipelines that do not hurt production. The next five posts are about the plumbing: copying database changes into a lake, a Kafka incident, a Redis speed-up, a DynamoDB cost trap, and how to budget latency across dependencies. They are where Swiggy is most open about what went wrong.

Lesson 15: CDC architecture for the data lake (2022)#

Assumptions.

  • Traffic: every row change in hundreds of MySQL and DynamoDB tables, flowing all day.
  • Latency: analysts want data within minutes to an hour, not the next morning.
  • Consistency: the lake copy must converge to exactly the source state; duplicates and out-of-order events are normal on the way.
  • Maintenance: teams change their table schemas without asking the data team, so pipelines must survive schema changes.

Dibyendu's post describes Swiggy's change data capture (CDC) architecture. CDC means reading a database's change log and streaming each insert, update and delete elsewhere, instead of copying whole tables with nightly queries. Nightly copies needed read replicas (called "slaves" in MySQL) that existed just for exports, and the data was a day old.

Tenets. Easy to use (onboard a table with config), elastic, cost-aware and reliable.

Sources.

  • MySQL binlog. MySQL's binary log can be statement-based (log the SQL text) or row-based (log the before and after values of each changed row). CDC needs row-based, because a statement like "UPDATE ... WHERE created < NOW()" gives different results when replayed later. Tools in this space include Maxwell, AWS DMS, Debezium, Airbnb's SpinalTap and Yelp's mysql_streamer.
  • DynamoDB Streams. Every change to a table appears as an INSERT, MODIFY or REMOVE record, with the new and old images of the item. Each change appears exactly once, in order per item.

Reconciliation challenges. Turning a stream of changes back into a table is harder than it sounds:

  • Schema: DynamoDB has no fixed schema, so the pipeline infers it at runtime from the items. Changes are classed as compatible (adding a column) or incompatible (changing a column's type), and incompatible ones need a human.
  • Correctness: the lake must match the source exactly.
  • Duplicates: at-least-once delivery means some events arrive twice.
  • Out-of-order events: events can arrive in a different order than they happened. Ordering uses the source transaction timestamp, not arrival time.

Optimised upsert. In each micro-batch, keep only the latest event per primary key and apply that. In the post's example, record R-001 had 16 events in one batch; only the last was applied. Record R-002's last event was a delete, so all its events were dropped and the row was deleted. This cuts write work sharply for hot rows.

Delta Lake. The target is Delta Lake: Parquet files plus a transaction log that adds ACID transactions to object storage. It supports MERGE (upsert), schema evolution, time travel (query a table as of an earlier version) and VACUUM (delete old files). Two maintenance jobs matter:

  • OPTIMIZE compacts many small files into fewer large ones. It cut one table's read time from 2 hours to 15 minutes.
  • Z-ordering on city and zone stores rows with similar values together, so queries filtering by city skip most files.

Tables are registered in a Hive metastore, queried with Spark SQL, and synced to Snowflake by an in-house job. The result was more than 20 percent monthly saving on database replicas and fresher data.

Overlooked constraints.

  • Small files kill lakes. Frequent micro-batches write many tiny files. Without compaction, reads slow down to the point the 2-hour example shows.
  • Timestamps must come from the source. Using arrival time to order events gives wrong final states when a partition lags.
  • Schema drift is a social problem. Upstream teams will rename columns. The pipeline must detect and block incompatible changes rather than silently writing nulls.

What Swiggy sacrificed. Simplicity. A nightly dump is easy to reason about; a streaming merge with dedupe, schema inference and compaction is not. The lake is also only eventually consistent with the source. A query during a batch can see a slightly older state.

Deep Dive: why keep-latest-per-key is correct, and the small-file mathsShow

Correctness (handbook's illustration). A row's final state depends only on its last event, if each event carries the full new image. For MySQL row-based logs and DynamoDB new images, it does. So within a batch, reducing to the event with the highest (source timestamp, log position) per key gives the same result as applying all events in order. Log position breaks ties when two changes share a timestamp. This only works with full images; if events were partial updates, you would need to fold them together instead.

Across batches. The MERGE must also guard against an older event arriving in a later batch. The condition is: update the target row only if the incoming source timestamp is newer than the stored one. This makes the merge idempotent and order-tolerant, the same trick as last-writer-wins registers.

Small files. If a table gets a micro-batch every 5 minutes across 200 partitions, that is 200 × 288 = 57,600 files a day. A query scanning a month opens 1.7 million files. With object storage at about 10 to 50 ms per open, that alone takes hours of serial time. OPTIMIZE to 1 GB files might leave a few thousand files. That explains how a 2-hour read could fall to 15 minutes.

Z-order. A Z-order curve interleaves the bits of two columns, so rows close in both city and zone land in the same file. Each file records min and max values per column. A query for one city can skip files whose range excludes it. The gain is largest when queries filter on the Z-ordered columns, and near zero otherwise.

Lesson 16: The Kafka bug story: when retries became a flood (2022)#

Assumptions.

  • Traffic: one Kafka cluster used by over 50 services that talk to each other in the order fulfilment journey.
  • Latency: checkout and trip services publish synchronously, so a publish failure becomes a user-facing error.
  • Consistency: producers require a minimum number of in-sync replicas (min ISR), choosing durability over availability.
  • Maintenance: clients in Java and Go, on library versions chosen by each team.

Abinash Sahoo's post, in Swiggy's #BehindTheBug series, walks through one January incident. A few partitions in an important Kafka cluster went offline for 4 minutes. That took down 18 services.

The timeline.

  1. Producers got NOT_ENOUGH_REPLICAS. This was expected: the topics required a minimum number of in-sync replicas, and there were not enough. The error is retryable.
  2. Clients were configured with linear backoff at 100 ms over a 10-minute window. Even so, ingress to the cluster rose about 100 times, and the cluster throttled clients.
  3. To cut the load, Swiggy reduced ordering coverage in its top 20 cities for nearly an hour and restarted services one by one.

The mystery. Go clients recovered by themselves. Only some Java clients did not. Their logs showed NOT_LEADER_FOR_PARTITION errors forever: they kept sending to a broker that was no longer the partition's leader. Normally the client refreshes its metadata (which broker leads which partition) and moves on. Here the metadata never refreshed. Its age climbed to about 5,000 seconds, when a healthy cluster stays under about 300.

The root cause. Just before the loop, every stuck client had thrown a NullPointerException while updating metadata. A known bug in the Java client explained it. The client could detect stale partition information using leader epochs, a feature added by KIP-320. But it always accepted the latest broker information. So its cached metadata could become a mix of two responses: a partition pointing to a leader whose broker details were missing. The code assumed that could never happen, hit a null, and got stuck in an inconsistent state. The bug report noted that a second race, without a lock, had long been possible but was very rare. KIP-320 made the first case possible, and partitions going offline is exactly when it happens.

The fix. Force-restarting the stuck clients made them fetch fresh metadata, and the platform was fully operational within two hours of the incident. Then the client library was upgraded; clients already on the latest version had recovered by themselves.

The 5-why analysis. Retries rose → producers sent to wrong leaders → metadata was wrong → a client bug left clients unable to update metadata after a null pointer.

Learnings.

  • Review retry policy. KIP-580 adds exponential backoff to Kafka clients, which avoids hammering a sick cluster.
  • Track client library updates proactively.
  • Wrap the Kafka client in an internal library. The wrapper made debugging easier and gave every client the same monitoring and alerts.

Overlooked constraints.

  • Retryable does not mean safe to retry fast. A fixed 100 ms backoff across thousands of producer instances is a coordinated flood. Backoff must grow and have jitter.
  • Client libraries are part of your distributed system. The broker was fine; a client bug turned a 4-minute blip into a two-hour incident. Mixed client versions mean mixed failure modes.
  • Durability settings shape availability. Requiring min ISR is right for order events, but it means partitions can refuse writes. Producers need a plan for that, such as a local buffer or a degraded path.

What Swiggy sacrificed. During the incident, revenue: coverage was cut on purpose in the 20 biggest cities. In design terms, the shared cluster for 50+ services made the platform simple to run, but a single cluster's problem reached the whole order path. Swiggy kept strict durability rather than accepting writes with fewer replicas.

Deep Dive: retry storms, exponential backoff and leader epochsShow

The flood in numbers (handbook's illustration). Suppose 2,000 producer instances normally send 500 batches a second each, 1 million requests a second in total. When partitions go offline, each failing send retries every 100 ms, and each instance has many in-flight batches, say 50, each retrying 10 times a second. That is 1,000 requests a second per instance just in retries, or 2 million a second on top of new traffic. Metadata requests add more. A 100-times jump on the affected paths is easy to reach.

Exponential backoff with jitter. Retry after min(cap, base × 2^attempt) multiplied by a random factor between 0 and 1 ("full jitter"). With base 100 ms and cap 10 s, the sixth retry waits up to 6.4 s. The total retry rate falls by orders of magnitude after a few attempts, and jitter spreads the retries so they do not arrive in waves. The AWS Builders' Library page covers this pattern in depth.

Leader epochs. Each time a partition gets a new leader, its leader epoch increases. KIP-320 let clients reject metadata with an older epoch than they already hold, which fixes a class of stale-leader bugs. But the broker list in a response is not epoch-tagged. A client that accepts a fresh partition record and keeps an older broker list can point at a broker it has no address for. That is the mixed-response case.

Retry budgets. Another guard is a retry budget: allow retries only up to, say, 10 percent of normal request volume per client. Beyond that, fail fast. This caps the flood no matter how many failures there are, and it is a standard pattern in large service meshes.

Lesson 17: Redis pipelining for the feature store#

Assumptions.

  • Traffic: thousands of Databricks jobs a day write ML features into Redis for online serving.
  • Latency: each write is cheap on the server; the problem is network round trips.
  • Consistency: features are written in bulk and read later; a partially written batch is retried.
  • Maintenance: the jobs were about 40 percent of the data science platform's maintenance cost.

Rahul Narayana's post starts from a cost problem. The DSP's feature store (where models read pre-computed features at serving time) sits on Amazon ElastiCache for Redis in cluster mode. Thousands of daily Databricks jobs load features into it. Those jobs made up about 40 percent of the platform's maintenance cost, and 50 to 70 percent of each job's time was spent writing to Redis.

Why it was slow. Redis executes a command in microseconds. But each command is a network round trip (RTT): the client sends, waits for the reply, then sends the next. With RTT around 0.5 ms inside a region, a single connection can do at most about 2,000 commands a second, no matter how fast Redis is.

Pipelining. Send many commands without waiting, then read all the replies at once. The round trip is paid once per batch instead of once per command. It also reduces system calls: one large write to the socket instead of many small ones means fewer switches between user mode and kernel mode, so CPU use falls on both client and server.

The sweet spot. Batches cannot grow without limit. Socket buffers and Redis's output buffers fill up, and a huge batch holds memory and delays the first reply. There is a batch size beyond which gains flatten and risks grow.

Cluster mode makes it harder. In Redis Cluster, keys are spread across 16,384 hash slots owned by different nodes. A pipeline must be split per node. When slots move during resharding, a node replies MOVED or ASK, and the client must redirect. Swiggy used Jedis 4.0, which added cluster pipelining, and wrapped it with:

  • a unified interface for jobs;
  • auto-sync when the pipeline reaches the batch size;
  • retry with exponential backoff for failed commands, including slot-moved redirects;
  • a fresh pipeline after each sync.

Results. About 90 percent less write time, about 60 percent lower cost for these jobs, and lower CPU.

Overlooked constraints.

  • Latency, not throughput, was the bottleneck. Bigger Redis nodes would not have helped; the server was mostly idle, waiting on the network.
  • Pipelining is not a transaction. Commands in a pipeline can partly fail. The wrapper must know which ones failed and retry only those, which is fine for idempotent SETs.
  • Cluster topology changes mid-batch. Any long bulk job will meet a resharding event eventually.

What Swiggy sacrificed. Per-write error handling and simplicity. Errors surface only at sync, so a failure is found later and must be retried in bulk. The team also owns a wrapper on top of Jedis that must track library changes.

Deep Dive: the round-trip arithmetic of pipeliningShow

One connection (handbook's illustration). RTT 0.5 ms, server time 10 µs per SET. Sequential: 0.51 ms per command, about 1,960 commands a second. Pipelined in batches of 500: one RTT plus 500 × 10 µs = 0.5 + 5 = 5.5 ms per batch, about 91,000 commands a second. That is about 46 times faster on one connection.

A job. Loading 50 million features sequentially at 1,960 a second on 8 connections takes about 53 minutes. Pipelined, it takes about 1.1 minutes plus overhead. The post's 90 percent cut in write time is consistent with this, after allowing for serialisation, retries and network variation.

Where it flattens. At batch size n, time per command is RTT/n + server time. Going from 500 to 5,000 saves only 0.9 µs per command, but buffers 10 times as many replies in memory. The curve flattens once RTT/n is small compared with server time, here around a few hundred to a few thousand commands.

Alternatives. MSET writes many keys in one command, but in cluster mode all keys must share a slot, which is rarely true. Lua scripts are atomic but have the same slot limit. Pipelining per node is the general answer. The Redis page covers cluster slots and replies in more detail.

Lesson 18: Limiting DynamoDB autoscaling: an on-demand guard rail (2022)#

Assumptions.

  • Traffic: normal application traffic plus occasional bulk jobs, such as loading over 1 TB of data before a launch.
  • Latency: the table must keep serving reads while capacity settings change.
  • Consistency: not affected; this is about capacity and cost, not data.
  • Maintenance: a guard rail that any team can attach to a table.

ayushi garg's post is a short, sharp cost lesson. DynamoDB has two capacity modes. Provisioned mode charges for the read and write capacity units (RCU and WCU) you reserve. On-demand mode charges per request and scales automatically. On-demand can instantly handle up to twice the previous peak. If traffic goes beyond double the previous peak within 30 minutes, requests may be throttled while it grows. The default account quota is 40,000 RCU and 40,000 WCU per table.

What went wrong. A team ran a prepopulation job writing over 1 TB into an on-demand table. On-demand did what it promises: it scaled the table up to its full capacity, and the bill spiked. Nothing failed technically; the danger was financial.

The guard rail.

  1. A CloudWatch alarm watches the SUM of consumed capacity on the table.
  2. When it fires, an EventBridge rule starts a Step Functions workflow.
  3. The First_switch Lambda moves the table from on-demand to provisioned at a low capacity. Writes beyond that capacity are throttled, which slows the bulk job instead of paying for it.
  4. Notify_and_Wait tells the owners.
  5. Wait_until waits 24 hours, because DynamoDB allows a switch between modes only once every 24 hours.
  6. Switch_db moves the table back to on-demand.
  7. Notify_Success or Notify_failure reports the outcome.

Two operational details matter. During a mode switch, the table's control-plane status is "updating", but reads and writes keep working. And if a switch is already in progress, a second request fails with ResourceInUseException, which the workflow must handle. Swiggy open-sourced the tool in May 2023 as ddb-ondemand-protector on GitHub.

Overlooked constraints.

  • Autoscaling has a cost dimension. Elastic services remove capacity outages but add bill outages. A runaway job can spend a month's budget in hours.
  • Control-plane limits shape the design. The once-per-24-hours switch rule is why the workflow waits so long.
  • Throttling is the brake. Moving to low provisioned capacity deliberately throttles the table. If live traffic shares that table, it is throttled too.

What Swiggy sacrificed. Elasticity for a day. Once the guard rail trips, the table cannot burst for 24 hours, so a real traffic spike in that window would be throttled. Swiggy chose a bounded bill over unbounded scaling.

Deep Dive: what a 1 TB load costs, and safer ways to do itShow

Write units (handbook's illustration). One WCU writes one item up to 1 KB per second. Loading 1 TB of 1 KB items is about 10^9 writes. In on-demand mode, each 1 KB write is one write request unit. List prices vary by region and have been cut over time, but at around one US dollar per million write request units that is on the order of 1,000 dollars, before indexes. Each global secondary index roughly doubles it. If the job retries or rewrites, or if items are larger than 1 KB, the cost multiplies.

The scaling side effect. On-demand tables also grow their partitions to absorb the peak. A table pushed to a very high write rate keeps those partitions afterwards. That is fine for cost in on-demand mode, but it changes how capacity is spread if the table later moves to provisioned mode.

Safer ways to bulk load. Write to a provisioned table with a fixed WCU and let the job take longer. Or, for a new table, use DynamoDB's import from S3, which loads data without consuming table write capacity. Or rate-limit the job in the client with a token bucket. The guard rail is the safety net when someone forgets.

The general pattern. Attach a budget circuit breaker to any auto-scaling resource: a metric, an alarm, an automatic action that caps capacity, and a notification. The same idea applies to serverless functions, autoscaling groups and managed stream services. See the capacity planning page and cloud architecture page for broader cost controls.

Lesson 19: Designing resilient microservices: adaptive latency budgets#

Assumptions.

  • Traffic: more than 400 microservices in production, over 130 of them on the order path from home page to doorstep.
  • Latency: each service promises an SLA to callers, for example 99.99 percent availability and 100 ms P99.
  • Consistency: a partial answer is often better than an error.
  • Maintenance: each dependency is owned by another team and changes continuously.

Vijay Seshadri's series asks how a service protects itself from its dependencies. The running example is a pricing service: the final price of a cart depends on catalogue prices, discounts, taxes and fees, each from a different service.

Two kinds of fault.

  • A blackout: the dependency is completely unavailable, for example because of a network partition. All requests fail.
  • A brownout: the dependency is partly available. Some requests fail, or they succeed but too slowly. Brownouts are common under resource pressure and harder to spot.

Both are detected with a circuit breaker: a wrapper that tracks failures and, past a threshold, stops calling the dependency for a while so it can recover.

Handling faults.

  • Graceful degradation. Return something useful instead of an error. For order tracking, if the DE's live location is unavailable, extrapolate an approximate position from the last known location, speed and route. Do this only for a time limit, then switch back to real data when the dependency recovers.
  • Careful retries. A service with N callers, each with M callers of its own, all retrying fast and often, creates a retry flood. That can push a dependency in brownout into blackout: a self-inflicted denial of service. Controlled retries, with fallbacks, keep the failure local and let the dependency heal.

Adaptive resilience. Say service M1 calls M2, M3 and a NoSQL store, and promises 100 ms at P99. The naive plan is a fixed budget: 30 ms each for M2, M3 and the store, plus 10 ms for M1's own logic. That has two problems. It ignores the real latency distributions of the dependencies. And even if it were right once, the dependencies keep changing, so it will drift.

The adaptive approach gives generous per-call timeouts and relies on a top-level timer. It uses one statistical fact: it is very unlikely that two dependencies both hit their P99 on the same request. If M2 takes 35 ms when its P99 is 30 ms, let it finish; M3 and the store are probably near their median on this request. The overall 100 ms timer still guarantees the caller's SLA: if it fires, the call graph is cancelled and an error returned. Swiggy implements this with gRPC deadlines and Go contexts, which pass the remaining deadline to every downstream call automatically.

Overlooked constraints.

  • Budgets drift with ownership. In microservices, each team ships independently. A latency budget written into config is wrong within months.
  • Deadlines must propagate. If M2 calls M4, M4 should know only 20 ms are left. Without propagation, downstream services do work whose result nobody will wait for.
  • Fallbacks need expiry. An extrapolated location is good for a minute and misleading after ten. Every degraded answer needs a time limit.

What Swiggy sacrificed. Strict per-dependency isolation. Generous timeouts let one slow dependency use more of the budget, so on rare requests where two are slow the whole call fails. Swiggy accepted a few more failures in the worst case for many more successes in the common case.

Deep Dive: the probability behind generous timeoutsShow

Fixed budget (handbook's illustration). Suppose each of M2, M3 and the store has a P99 of 30 ms and independent latencies. With a 30 ms timeout on each, a request fails if any one exceeds 30 ms: probability 1 − 0.99³ ≈ 3 percent. That is far worse than the 1 percent that a 100 ms P99 promise allows.

Adaptive budget. Run M2, M3 and the store in parallel, with timeouts of 90 ms each and a 100 ms overall timer. If each has a P99.9 of 80 ms, the chance any exceeds 90 ms is under 0.3 percent. For sequential calls, the sum matters. With medians of 10 ms and P99s of 30 ms, the sum of three rarely exceeds 70 ms. One call at its P99 plus two at their medians is 50 ms, comfortably inside the budget. Two at P99 at once happens about 3 times in 10,000 requests under independence.

When independence fails. If all three share a database or a network link, their slow moments are correlated. Then two P99s together are much more likely, and the top-level timer fires more often. Measuring correlation between dependency latencies is worth doing before trusting this model.

Go and gRPC. A Go context created with a 100 ms deadline is passed to each gRPC call. gRPC sends the remaining time to the server in a header. The server's context then expires at the same moment, so it can stop work early. When the top-level context is cancelled, every in-flight call is cancelled with it. The resilience patterns page covers timeouts, bulkheads and circuit breakers in general.

Family 6: Customer-facing systems

The last group of posts faces the customer, the rider and the payment network directly. Ranking decides what you see; search decides how fast you find it; experiments decide which version ships; notifications and the apps carry the result to your phone; and payment routing decides whether you can pay at all.

Lesson 20: Feed ranking: from popularity to learned ranking (2019)#

Assumptions.

  • Traffic: every app open renders the listing page, Swiggy's main discovery surface.
  • Latency: ranking runs inside the listing call, after serviceability, so it must be fast.
  • Consistency: rankings can be personal and change hourly; no one expects two users to see the same order.
  • Maintenance: cities differ a lot, so one model may not win everywhere.

Jairaj Sathyanarayana and Nitin Hardeniya describe how the listing feed evolved. The scale of choice is the problem. In Bengaluru's Koramangala alone there were over 700 restaurants, each with about 100 items. A hungry customer will not scroll through 70,000 dishes.

What "good" means. The team tracked many metrics:

  • ranking metrics: nDCG (normalised discounted cumulative gain, which rewards relevant items near the top) and MRR (mean reciprocal rank, 1 divided by the position of the first relevant item);
  • behaviour metrics: click depth, ordered-click depth (how far down the restaurant they ordered from was), the share of orders from the top X slots, and the share of sessions that needed search;
  • business metrics: brand and cuisine mix, and last-mile distance (a feed that pushes far restaurants costs more to deliver).

The overall evaluation criterion (OEC, the single metric experiments are judged on) was orders per device. Food intent is high and short-term: the customer will eat in 30 to 60 minutes, so conversion is the right goal.

Experiments. A/B tests used PlanOut (an open-source framework from Facebook for defining experiments). Tests ran within cities, stratified by city age, with a holdout on the popularity ranker. A key finding: no single ranker won in every city.

Three generations of rankers.

  1. Popularity: rank by recent orders. Simple and strong, but the same for everyone.
  2. Multiplicative utility: score = customer preference × restaurant similarity × popularity. Easy to extend with new factors, but the weights were tuned by hand.
  3. Pointwise GBDT: a gradient-boosted decision tree classifier in Spark MLlib, predicting whether a customer will order from a restaurant. Features exist at the customer level, the restaurant level and the customer-restaurant pair level.

Restaurant similarity for cold start. To compare restaurants, each one's menu is turned into a topic vector with LDA (latent Dirichlet allocation, a model that finds topics in text). Cosine similarity between vectors measures how alike two restaurants are. This lets a new restaurant inherit interest from similar ones. A trap is menu stuffing: some restaurants list hundreds of items to appear in more searches. For restaurants with 30 to 90 days of order history, only items that have actually been ordered are used.

Next steps at the time were multi-objective optimisation, learning-to-rank with TF-Ranking, and embeddings.

Overlooked constraints.

  • Ranking changes logistics. A feed that promotes far restaurants raises last-mile cost and stress. Ranking metrics must include delivery cost.
  • Supply-side gaming. Restaurants respond to the ranker. Menu stuffing shows that any signal sellers control will be gamed.
  • Cities are different markets. A new city with few restaurants behaves unlike a mature one. Stratifying by city age avoids averaging away real effects.

What Swiggy sacrificed. A single global model. Running different rankers per city is more work to maintain and explain. Pointwise classification also ignores how items compare with each other on the page, which pairwise or listwise learning-to-rank would capture.

Deep Dive: nDCG and MRR with a worked feedShow

Worked example (handbook's illustration). A feed shows five restaurants. The customer clicked positions 2 and 5 and ordered from 2. Using relevance 2 for "ordered", 1 for "clicked", 0 otherwise: gains are 0, 2, 0, 0, 1. DCG = sum of gain / log2(position + 1) = 2/1.585 + 1/2.585 = 1.262 + 0.387 = 1.649. The ideal order is 2, 1, 0, 0, 0: IDCG = 2/1 + 1/1.585 = 2.631. nDCG = 1.649 / 2.631 = 0.63. MRR for "first ordered item" is 1/2 = 0.5.

Why pointwise is a start. A pointwise model predicts P(order) per restaurant and sorts. It is easy to train with standard tools. But the loss does not know about positions: getting the top slot right matters more than slot 40. Pairwise methods (RankNet) and listwise methods (LambdaMART, which weights pair swaps by their effect on nDCG) optimise the ranking directly. Lesson 21 shows Swiggy using LambdaMART for autocomplete.

Multiplicative scores. With score = a × b × c, a zero in any factor kills the item, and doubling any factor doubles the score. That is easy to reason about but brittle: a missing preference value for a new user is zero, not "unknown". Adding a small floor, or using a learned model, avoids this.

Position bias. Items at the top get clicked partly because they are at the top. Training on raw clicks teaches the model its own past ranking. Holdouts and randomised slots, as in the popularity holdout here, give cleaner data.

Lesson 21: Search and autocomplete ranking (2020 and 2026)#

Assumptions.

  • Traffic: autocomplete fires on every keystroke. Typing "biryani" sends seven requests.
  • Latency: ranking must take under 10 ms so suggestions keep pace with typing.
  • Consistency: suggestions can be slightly stale; popular dishes do not change minute to minute.
  • Maintenance: the search app screen was rebuilt to stop UI changes needing app releases.

Two posts cover search. The first, by Viswanathan K P, rebuilt the search screen in the app. The second, by Ramkishore Saravanan, rebuilt autocomplete ranking.

The app rewrite (2020). The old search screen had huge ViewModels (about 2,000 lines) and dead feature flags. The rewrite brought:

  • Backend-driven UI: the server sends a list of widgets and their data, and the app renders them. New layouts ship without an app update.
  • A stack-based state manager for moving between search states.
  • Reusable ViewModels.
  • DiffCover gating: new code must meet a unit-test coverage bar.
  • Protocol Buffers instead of JSON: responses were about 12 percent smaller, and the schema is a strict contract shared by server and app.
  • Analytics events defined by the backend.

The app also became lighter to draw: less GPU overdraw, about half as many nested layouts (for example, LinearLayouts down from 41 to 21), and fewer bitmaps (34 to 19).

Autocomplete with learning-to-rank (2026). The old ranker used OpenSearch's function_score: a hand-written formula mixing text match and popularity. It failed in four ways:

  • balancing fuzzy matches against popular items was guesswork;
  • it had no signal for what people actually ordered;
  • it had to rank different types (dish, restaurant, cuisine, brand) against each other;
  • every change was manual tuning.

The fix was the OpenSearch Learning to Rank (LTR) plugin. It runs model inference inside the search engine, so there is no extra network hop. It works in two phases: a cheap query retrieves candidates, then the model rescores only the top k. It supports RankLib, XGBoost and linear models, and defines features with Mustache templates (small query snippets with parameters).

Two retrieval flows feed it: partial prefix matching for what the user is typing, and semantic templates for intent.

The steps.

  1. Create the LTR store in the cluster.
  2. Stabilise the first-phase query, so features are computed on a fixed candidate set.
  3. Define a featureset: each feature is a templated query whose score becomes a number.
  4. Log features for real searches with the sltr query and ltr_log extension, then join them with clicks, add-to-carts and orders to make labelled training data in SVM-rank format.
  5. Train on Databricks with RankLib, trying LambdaMART, random forests and RankNet. Evaluate with MRR and nDCG.
  6. Upload the model and use it in a rescore clause.

Part 2 of the series was to cover personalisation.

Overlooked constraints.

  • Training-serving skew. If features are computed differently when training and when serving, the model learns the wrong thing. Logging features from the engine itself avoids skew.
  • Every keystroke is a query. Seven requests per word multiplies load. Debouncing in the app and caching popular prefixes matter as much as the model.
  • Mixed result types. A dish and a restaurant are not comparable by text score. A learned model on shared features is what makes cross-type ranking possible.

What Swiggy sacrificed. The engine is now doing ML inference, which makes the search cluster more complex to size and debug. The rescore window k caps quality: an item outside the first-phase top k is never seen by the model.

Deep Dive: two-phase ranking and the query cache in front of itShow

Two-phase cost (handbook's illustration). Suppose the first phase matches 5,000 documents per shard and scores each with BM25 in about 0.2 µs: 1 ms. Running a 300-tree LambdaMART model on each would cost about 300 tree walks × 5,000 documents, around 30 ms. Rescoring only the top 100 costs 0.6 ms. The total stays inside the 10 ms ranking budget. The trade-off is recall: the first phase must be good enough that the best item is in the top 100.

LambdaMART in one paragraph. LambdaMART (Burges, "From RankNet to LambdaRank to LambdaMART: An Overview", Microsoft Research, 2010) is gradient-boosted trees trained with "lambda" gradients. For each pair of documents in the wrong order, the gradient is scaled by how much swapping them would change nDCG. So the model focuses on mistakes near the top of the list.

A query cache for prefixes. Most keystrokes are common prefixes. A cache keyed by (normalised prefix, city, maybe customer segment) with a short TTL can absorb a large share of traffic. Sizing it follows the classic estimate: if 10 million distinct keys are hot and each response is about 1 KB, the cache is about 10 GB. Use LRU eviction (a hash map plus a doubly linked list gives O(1) get and put). Shard it across nodes with consistent hashing so adding a node moves only a fraction of keys. The cache must expire entries when popularity or menus change, so TTL matters more than eviction. Personalised results either skip the cache or include the segment in the key. For one-minute freshness, a TTL under a minute is enough; a CDN with cache-control headers can serve the most common non-personalised prefixes from the edge in tens of milliseconds instead of hundreds.

Scatter-gather. A search cluster splits the index into shards. A query goes to every shard, each returns its top results, and a coordinator merges, ranks and sorts them. This is the same scatter-gather shape as large social search systems. The coordinator's merge cost grows with shards × k, which is another reason to keep k small. The Elasticsearch page covers shard sizing.

Lesson 22: Building the experimentation platform (2021)#

Assumptions.

  • Traffic: many experiments at once across consumer, vendor, rider and location surfaces.
  • Latency: allocation must be a fast, local, deterministic function of the unit ID.
  • Consistency: a user must see the same variant every time, or the experiment is invalid.
  • Maintenance: the number of cities grew from about 10 in 2017 to over 500 in 2020, and many teams run tests.

Amaresh M's two-part series describes Swiggy's experimentation platform (XP). The goals were speed of experiments, accurate measurement (including checks for sample ratio mismatch, SRM, explained below) and democratisation, so any team can run a test. An XP Council reviews practices.

What gets tested. Experiments are grouped by who they target: Consumer, Vendor, DE and Location. The unit of randomisation can be a user, a device or a session ID.

Layers called pods. Swiggy's design follows Google's paper on overlapping experiment infrastructure (Tang, Agarwal, O'Brien and Meyer, "Overlapping Experiment Infrastructure: More, Better, Faster Experimentation", KDD 2010). Experiments change config parameters. Parameters are grouped into pods (Google calls them layers). A user is in at most one experiment per pod, but can be in experiments in several pods at once. Domains decide how pods interact: exclusive (no overlap), conservative, or overlapping.

Allotment methods.

  • Uniform or weighted random splits.
  • Time-sliced randomised: switch variants over time windows, chosen at random.
  • Time-sliced deterministic (a switchback): alternate variants on a fixed schedule. This is essential for marketplace tests. If you give half the riders in a zone a new assignment algorithm, the two halves compete for the same orders, and the test is contaminated. Switching the whole zone between variants over time avoids that.

The lifecycle.

  1. Ideate: a hypothesis stating What, How and Why.
  2. Design: a template with metrics, a sample-size calculator, a duration calculator and the target audience.
  3. Set up: test in staging with test devices, then ramp from 5 percent.
  4. Track: watch allocation and metrics, with alerts and the option to ramp down.
  5. Analyse: logging, significance tests (including methods for switchbacks and difference-in-differences), SRM checks, and flicker checks (users who saw more than one variant).
  6. Iterate: run new instances of the experiment.

Overlooked constraints.

  • Marketplaces break independence. Standard A/B tests assume one user's variant does not affect another's. Riders and orders are shared, so switchbacks and geography-based splits are needed.
  • Interaction between experiments. Two tests on the same parameters can cancel or amplify each other. Pods and domains make that explicit.
  • Allocation bugs look like results. A 50/50 split that comes out 52/48 over a million users is not chance. SRM checks catch broken allocation before anyone trusts the result.

What Swiggy sacrificed. Speed for some tests. Switchbacks need many time windows to reach significance, so they run longer. Pods also limit how many experiments can touch the same parameters at once. See the experimentation platform case study for the full design.

Deep Dive: SRM, sample size and switchback analysisShow

SRM test (handbook's illustration). Intended split 50/50, observed 501,200 control and 498,800 treatment. Expected 500,000 each. Chi-square = 1,200²/500,000 + 1,200²/500,000 = 5.76. With one degree of freedom, the p-value is about 0.016. At the strict thresholds used for SRM, such as p below 0.001, this would not trigger, but it is worth watching. A 503,000 / 497,000 split gives chi-square 36 and a p-value around 2 × 10^-9: something is broken.

Sample size. To detect a lift from 10.0 to 10.3 percent conversion (a 3 percent relative change) with 80 percent power at 5 percent significance, n per arm ≈ 16 × p(1 − p) / δ² = 16 × 0.1 × 0.9 / 0.003² = 160,000. A duration calculator then divides by daily eligible users.

Switchback analysis. Suppose a zone alternates A and B every hour for two weeks: 336 windows, 168 each. The unit of analysis is the window, not the order, because orders within a window are correlated. Compare mean delivery time per window between A and B with a t-test on 168 versus 168. Short windows give more samples but more carry-over: riders assigned under A still deliver during B's hour. Dropping the first few minutes of each window reduces that bias.

Hashing for allocation. bucket = hash(unit_id + pod_salt) mod 1000. Using a different salt per pod makes pods independent of each other, which is the core trick of the layered design.

Lesson 23: Kabootar communications platform (2017)#

Assumptions.

  • Traffic: push, SMS and email to customers, riders, restaurants and support agents; transactional and marketing traffic mixed.
  • Latency: transactional messages ("your order is on the way") within seconds; marketing can wait.
  • Consistency: at-least-once delivery with retries and fallbacks; the sender can ask to be told when the message was routed.
  • Maintenance: used by every team, so templates and campaigns are managed through a UI, not code.

Before Kabootar ("pigeon" in Hindi), each team sent its own notifications from inside its own services. That was fine while teams were small. Siddhant Srivastava's 2017 post describes the shared platform that replaced it.

Requirements. One place for transactional and marketing messages, with different priorities. Retry and fallback. Templates with context that can be rendered. Scheduling. Templates grouped into campaigns, which also track open rates, click-through actions (CTAs) and conversions, and allow filtering and enrichment.

The self-contained MESSAGE. Every communication travels as a single MESSAGE object that holds everything needed to send it. Because it carries no outside state, any node can process it. That is what makes the system easy to distribute.

The pipeline. The platform has eight microservices connected by a RabbitMQ backbone:

  1. Event service: receives events, classifies them, and enriches them with user information.
  2. Campaign service: builds message objects and applies campaign settings.
  3. Templating service: renders the template and embeds tracking.
  4. Router: picks the channel and pushes to the right gateway (push, SMS or email provider).

Each domain (event, message, campaign, tracker) has a state machine that is persisted continuously. If a message is stuck in a non-final state, another worker can pick it up.

Why pull, not push. Chaining services with HTTP or RPC means a burst can overwhelm a downstream service. With queues, each service pulls at its own pace. Each service has three layers: an integration layer that accepts HTTP or queue input, a core logic layer, and a consumer layer that sends output. So a service can read from RabbitMQ and write to Kafka without changing its core logic. The team modelled this on Enterprise Integration Patterns.

User data via Grand Maester. Campaigns need user details. Rather than every team collecting data about users it does not own, a central aggregation service called Grand Maester lets teams register APIs that return user information.

Fallback as a deque. Retry and fallback rules live inside the message, not in a database. "Send template T1, retry twice, then fall back to T2 and retry once" is stored as a deque [T1, T1, T1, T2, T2]. To send, pop the next template. On failure, inspect the error: a rendering error skips straight to the fallback, since retrying the same template would fail again. Keeping this inside the message avoids slow lookups in an append-only store.

Samay, the scheduler. Scheduled campaigns, time-based state transitions and reports all need a scheduler. Samay ("time" in Hindi) wraps Quartz. Users register crons or one-time triggers, with metadata, and choose a queue, topic or webhook for notification. Events are Ack (the consumer must confirm receipt, possibly asynchronously) or No-Ack. Samay is shipped as a library jar inside every microservice: if any service is up, the scheduler is up, with no extra machines.

Storage and reporting. MySQL is the transactional store; Elasticsearch serves aggregation, reporting and ad-hoc queries. An hourly cron aggregates campaign metrics (dispatch, failure, delivery, open and click rates), and per-user detail is produced on request by a MapReduce job.

Performance. On four m4.xlarge machines, with one instance of each service, the system processed one million messages in 15 minutes, about 1,100 a second.

Overlooked constraints.

  • Priority needs separate lanes. If marketing blasts share a queue with "your OTP", the OTP waits behind a million promos. Separate queues or priority consumers are required.
  • Provider limits. SMS and push gateways rate-limit senders. The router must pace output, or a campaign will be throttled by the provider.
  • Embedded schedulers need coordination. A scheduler jar in every service must ensure a trigger fires once, not once per instance. Quartz's clustered mode with a shared database lock is the usual way.

What Swiggy sacrificed. End-to-end latency and simplicity. Four queue hops add delay to every message. A central platform also becomes a shared dependency: when it is slow, every team's notifications are slow. See the notification system case study for a full design.

Deep Dive: throughput, priorities and the dequeShow

Throughput (handbook's illustration). One million messages in 15 minutes is about 1,100 a second on four machines with one instance of each service. A dinner-time order surge at 1,000 orders a minute might create 5 transactional messages each, about 83 a second, well within capacity. A marketing blast to 20 million users is the real load: at 1,100 a second it takes about 5 hours. Scaling each stage horizontally, which the stateless MESSAGE allows, brings that to under an hour with 6 instances per stage.

Priority lanes. Use two RabbitMQ queues per stage, transactional and marketing, with consumers that drain transactional first. Or give transactional work its own consumer pool. RabbitMQ also supports per-message priorities on a priority queue, but separate queues are easier to monitor.

Deque semantics. For [T1, T1, T1, T2, T2]: pop T1 and send. If the gateway fails, pop again: still T1. After three T1 failures, the next pop is T2. If T1 fails to render, the handler drops all remaining T1 entries and pops T2. The deque turns the retry policy into data that travels with the message, so no central lookup is needed. The cost is that changing a policy does not affect messages already in flight.

Ack versus No-Ack. An Ack event is re-sent until acknowledged, which gives at-least-once delivery; the consumer must be idempotent. A No-Ack event is fire-and-forget, at-most-once. Reports can use No-Ack; state-machine timeouts need Ack.

Lesson 24: Cache on delivery for hybrid pages, and order tracking in picture-in-picture (2018)#

Assumptions.

  • Traffic: low-interaction pages (Help, FAQ, terms, experiments) shown inside the app as web pages, on phones with patchy 3G.
  • Latency: a native-feeling page should load in about a second; the Help page took about 13 seconds on good 3G.
  • Consistency: cached assets must match the deployed web version; a stale bundle can break the page.
  • Maintenance: the web team deploys independently of app releases, which is the whole point of hybrid pages.

Manjunath Chandrashekar wrote two short app posts in 2018. Both are about making the app feel fast and calm without new backend systems.

Cache on delivery. Swiggy shows some pages in a WebView (Android) or WKWebView (iOS), an embedded browser inside the app. Web pages keep the app small, ship updates over the air and work on both platforms. But they were slow. The Help and Support page took about 13 seconds on good 3G. Most of that was downloading JavaScript, fonts and images. The built-in WebView cache did not help enough. Cache-control headers were not reliably honoured across app launches, behaved differently across devices, and did nothing for the very first load.

So the team built its own cache inside the app:

  1. At app start, fetch a list of all assets the web pages need.
  2. Download them asynchronously in the background.
  3. Save them on the device.
  4. When the WebView asks for an asset, intercept the request and serve the local copy.

On Android, the hook is shouldInterceptRequest on WebViewClient, which is called for every resource request. The web app is built with Webpack, which splits JavaScript into chunks loaded on demand. The build produces a manifest mapping every asset (JavaScript, CSS, fonts, images). A simple resources API serves that manifest to the app.

The app side has four modules:

  • Resource Config Manager: syncs the manifest. It keeps an overall config version and per-feature versions; a version mismatch flushes old assets. A hash per asset means only new or changed files are downloaded.
  • Interceptor: serves cached files when present.
  • Download Manager: fetches assets to a temporary folder.
  • Cache Manager: tracks expiry as configured.

The Help page became about 96 percent faster. The onboarding pages for the Swiggy SUPER membership became about 79 percent faster on good 3G. The post is honest about the costs: a strict contract between the web and app teams, invalidating stale caches, handling API and bundle download failures, and corrupted bundles. iOS WKWebView turned out to be harder.

Order tracking in picture-in-picture. Data showed customers return to the tracking screen many times during the 20 to 45 minutes of a delivery. To reduce that anxiety, Swiggy made tracking available in picture-in-picture (PIP) mode on Android O and later: a small floating window that stays on screen while the customer uses other apps. The activity declares PIP support in the manifest. When the user leaves the app (onUserLeaveHint), the app enters PIP with a 3:4 aspect ratio.

Two problems came from the app's multi-activity structure. First, PIP could create multiple instances of the app; the workaround was to finish other tasks and exclude PIP from the recent-apps list. Second, tapping a notification or deep link while in PIP opened the target screen inside the tiny PIP window. The fixes were to disable app shortcuts during PIP and, longer term, to move to a single-activity app with fragments. The feature was built in two days and had over 30,000 PIP impressions in its first week.

Overlooked constraints.

  • The first load matters most. Browser caches help repeat visits. On a new install, nothing is cached, and that is when users judge the app.
  • Two teams, one contract. The manifest format, version rules and hash scheme are an API between web and app teams. Changing it on one side breaks the other.
  • Platform quirks decide scope. PIP only existed on Android O and later, and WKWebView did not offer the same interception. The feature is only as wide as the platform allows.

What Swiggy sacrificed. Storage and data on the phone. Prefetching assets at app start uses bandwidth the user may never need. It also gave up the simplicity of "just a web page": hybrid pages now depend on app-side code. PIP added another app state to test.

Deep Dive: why 13 seconds becomes half a secondShow

The budget (handbook's illustration). On good 3G, around 1.5 Mbit/s with 150 to 300 ms round trips, a page needing 800 KB of JavaScript, 200 KB of fonts and 300 KB of images must transfer 1.3 MB: about 7 seconds of pure transfer. Add DNS, TLS and connection setup for several hosts (2 to 3 round trips each), request waterfalls where one script loads the next, and parse time on a mid-range phone. 13 seconds is believable.

With a local cache. Transfer falls to near zero; only the HTML and API data cross the network, perhaps 30 KB, under 300 ms. Parse and render remain, perhaps 200 to 300 ms. That is roughly a 95 percent cut, in line with the post's 96 percent.

Versioning. Content-hashed filenames (app.3f9a.js) are the standard cache-busting trick: a new build gives new names, so stale files are never served by mistake. The manifest maps logical names to hashed names. Flushing on a version mismatch is the safety valve for changes the hashes do not cover.

Same idea on the server. This is a client-side CDN: push assets close to the user before they are needed. Web apps today often use service workers for the same purpose. The CDN page and caching strategies page cover the server-side version.

Lesson 25: Architecture of the delivery partner app (2019)#

Assumptions.

  • Traffic: one long session per rider, on average 4 to 5 hours, mostly running in the background.
  • Latency: order offers must show within seconds even on weak networks.
  • Consistency: the server is the source of truth for orders; the app must reconcile after going offline.
  • Maintenance: many cities, many phone models, and frequent changes, so features must roll out gradually and be switchable remotely.

Narendra's post is the third in a series on rebuilding the app riders use. It is a good example of system design on the device.

Design principles.

  • KISS (keep it simple): the app must track location, sync orders and talk to GPS, network, Bluetooth and sensors for hours. Doing that on the JavaScript UI thread would make the UI stutter. So only the UI is in React Native; long-running, background and storage work is native (Android and iOS).
  • Separation of concerns: user interaction, business logic, sync, storage, network and instrumentation each live in their own module or framework.
  • Modular and DRY (don't repeat yourself): components are built to be app-agnostic so they can be shared across the Consumer, Delivery, Vendor and Daily apps.
  • Inversion of control: "don't call us, we'll call you" (the Hollywood principle). Modules receive their dependencies instead of creating them, using Dagger 2 for dependency injection, and a retry framework calls back into features rather than each feature writing its own retry loop.

Patterns.

  • Unidirectional data flow: server → native storage (the app's source of truth) → Redux store → UI. User actions go back through a native sync module to the server. Data only flows one way around the loop, which makes state easy to reason about.
  • Pub-sub with RxJava: modules publish and subscribe to events instead of calling each other.
  • A state machine per delivery: each order moves through clear states, and the UI shows what the current state allows.

Offline and bad networks. Critical flows are kept light. Non-critical data is synced lazily. Retries use configurable policies (exponential, linear or Fibonacci backoff). BCP modes (business continuity) keep riders working when parts of the backend are down.

Observability on the phone. A real-time logger can be switched on remotely for one rider to debug a live problem. New Relic tracks network metrics. Crashlytics reports crashes, wired to PagerDuty and Slack. Firebase Remote Config switches features by city, zone or OS version. Rollouts are gradual, and the app was stable for 99.9 percent of users.

Overlooked constraints.

  • The battery is a resource budget. Hours of GPS and network use drain phones. Ping frequency and wake-ups are a design parameter with real cost to the rider.
  • Offline is normal. Basements, lifts and dead zones are part of every delivery. An action taken offline must be queued, retried and applied once.
  • Remote control is a safety system. Feature flags by city and a remote logger let the team fix problems without waiting days for app store review.

What Swiggy sacrificed. One codebase. A React Native UI over native modules means three languages and two bridges to maintain. The team accepted that cost for a smooth UI and reliable background work.

Deep Dive: queuing offline actions and choosing backoffShow

Offline queue (handbook's illustration). When a rider taps "picked up" in a basement, the sync module writes the action to local storage with a client-generated ID and timestamp, updates the local state at once, and tries to send. If sending fails, it retries with backoff. The server treats the client ID as an idempotency key, so a duplicate send after a timeout does not apply twice. If the server rejects the action (the order was cancelled meanwhile), the local state rolls back to the server's version, because the server is the source of truth.

Backoff choices. Exponential (1, 2, 4, 8, 16 s) backs off fastest and suits server outages. Linear (2, 4, 6, 8 s) keeps trying steadily, which suits short signal drops. Fibonacci (1, 1, 2, 3, 5, 8 s) sits between them. Over 60 seconds, exponential makes about 6 attempts, Fibonacci about 9 and linear about 7 with a 2 s step. Choosing per action type lets critical actions retry more eagerly.

Location pings. At one ping every 5 seconds over a 5-hour session, a rider sends 3,600 pings. At about 200 bytes each that is about 720 KB, small for data but costly for battery if each send wakes the radio. Batching pings every 30 seconds when the rider is idle cuts radio wake-ups by six times. Sending immediately on state changes keeps assignment accurate.

Related pages. See realtime communication for how the server pushes offers, and observability for the server-side half of the monitoring story.

Lesson 26: ML payment routing (2022)#

Assumptions.

  • Traffic: every online payment on the platform, split across cards, UPI (India's real-time bank payment system), net banking and wallets.
  • Latency: the routing decision adds only milliseconds before the customer is sent to a gateway.
  • Consistency: success rates must be fresh, from the last minutes to days, because gateway health changes quickly.
  • Maintenance: gateways improve, degrade and change prices; the model must notice without manual rules.

Mithun T M and Ashay Tamhane explain how Swiggy picks a payment gateway (PG) for each transaction. A PG passes payment details between Swiggy and the bank or card network. Several PGs can handle the same method, and their payment success rate (PSR) differs by bank, card and time. A failed payment can lose the order and the customer.

Swiggy built one model per payment method, for two reasons: the same PG performs differently on different methods, and the set of eligible PGs differs by method.

Net banking: epsilon-greedy. The key signal is how well each bank works with each PG recently. Some bank and PG combinations have few recent transactions, so the system uses explore-exploit with epsilon-greedy:

  • Explore (20 percent): route to a PG uniformly at random. This keeps estimates fresh for every PG and gives unbiased data for evaluation. The 20 percent figure came from minute-level traffic analysis: enough to estimate PG success rates for the top banks.
  • Exploit (80 percent): a rule-based score from bank-and-PG success rates over the last 4 hours, 1 day and 7 days, plus the PG's overall success rate over the last 5 minutes. It uses the most recent window with data. Route to the highest score.

UPI: sampling from a Beta distribution. Before this, UPI routing was essentially random, even though PG success rates differed a lot. The new model is Thompson sampling. For each PG, take the successes and failures in the last 15 minutes as the α and β of a Beta distribution, which describes uncertainty about a success probability. Draw one random sample per PG and route to the highest. With 5 successes and 5 failures, Beta(5, 5) has mean 0.5 but a wide spread, so the PG sometimes wins by chance: exploration. With 50 and 50, Beta(50, 50) has the same mean but a narrow spread: exploitation. Less data means more exploration, automatically. Another 5 percent is routed at random for clean data. In an A/B test, PSR rose 1.5 percentage points and a conversion metric rose 0.25 points.

Cards: from GBT to logistic regression, with cost.

  1. The first version was rules, like net banking.
  2. Then a gradient-boosted tree model, trained on history, predicted the probability of success for each of four PGs from card attributes and success-rate trends.
  3. A cost step divides each PG's predicted success probability by its price. That cut PG cost about 7 percent at the same PSR, in an A/B test against the rule-based model.
  4. Non-stationarity: if card C1 works best with PG1 in June, a greedy model sends all C1 traffic to PG1. If PG2 improves by September, the model never sees it. The fix was 5 percent epsilon-greedy exploration, enough to estimate PG success rates for the top cards that make up 80 percent of transactions.
  5. The exploit model was then changed to logistic regression, because the team kept having to explain individual routing decisions and the trees made that hard. In an online A/B test it matched the trees on PSR and cost.

Overlooked constraints.

  • Greedy routing blinds itself. Sending all traffic to today's best gateway stops you learning tomorrow's. Exploration is not waste; it is the cost of staying informed.
  • Explainability is a requirement. Payments involve partners, finance and incident reviews. A model nobody can explain will be overruled by rules, so a slightly simpler model that can be explained wins.
  • Cost is part of the objective. Gateways charge different fees. Maximising success alone can be expensive; dividing by price gives a simple trade-off.

What Swiggy sacrificed. Some success rate on the exploring share. Sending 5 to 20 percent of traffic randomly means some transactions go to a worse gateway. Swiggy also gave up the small accuracy edge of trees for explainability. See the payment system case study for how routing fits in a full payment flow.

Deep Dive: the maths of exploration in payment routingShow

Beta spread (handbook's illustration). A Beta(α, β) distribution has mean α/(α + β) and variance αβ / ((α + β)² (α + β + 1)). For Beta(5, 5) the standard deviation is about 0.15. For Beta(50, 50) it is about 0.05. Suppose PG2 has Beta(80, 20) (mean 0.8, sd 0.04) and a new PG3 has Beta(3, 1) (mean 0.75, sd 0.19). PG3 will beat PG2 in nearly half of all samples (P of a Beta(3, 1) draw above 0.8 is 1 − 0.8³ ≈ 0.49), so it gets real traffic until its data shows its true rate. If it is truly at 0.75, its distribution narrows and its share falls. This is how Thompson sampling balances exploration automatically (Thompson's 1933 paper in Biometrika introduced the idea).

The cost of epsilon. With 20 percent random routing across 4 PGs, and success rates 0.90, 0.88, 0.85 and 0.80, the random share averages 0.8575 against 0.90 for the best. The loss is 0.2 × (0.90 − 0.8575) = 0.85 percentage points of PSR overall. At 1 million transactions a day, that is about 8,500 failed payments that exploitation would have saved, many of which customers retry successfully. That is why the cards model uses only 5 percent, and why Thompson sampling, whose exploration falls as data grows, suits UPI's high volume.

Cost-adjusted score. For PG1 with P(success) 0.92 at a 1.8 percent fee, and PG2 with 0.90 at 1.5 percent: 0.92 / 1.8 = 0.511 and 0.90 / 1.5 = 0.600. PG2 wins despite lower success. A business can tune this by using P(success) divided by fee raised to a power: a power of 0 ignores cost; 1 is the post's rule.

Windows. A 5-minute window catches a gateway outage fast but is noisy. A 7-day window is stable but slow. Using the most recent window with enough data, as the net banking rule does, is a simple form of adaptive smoothing.

Family 7: Synthesis

Lesson 27: What the Swiggy posts teach when read together#

Assumptions.

  • Traffic: read paths (home, listing, search, tracking) outnumber write paths (orders, payments) by orders of magnitude, and both peak sharply at lunch and dinner.
  • Latency: every customer-facing step has a budget of tens to a few hundred milliseconds, while optimisers and forecasts run on cycles of minutes.
  • Consistency: money and task state must be exact; almost everything else (distance, stress, ETAs, rankings, geo indexes) is allowed to be a little stale.
  • Maintenance: hundreds of services owned by many teams, with physical-world inputs (roads, weather, riders) that no team controls.

Read one at a time, these posts look like separate topics: maps, ML, Kafka, mobile apps. Read together, they show one shape. Swiggy runs a physical system with inelastic supply (riders, kitchens, roads) behind a digital system with elastic demand (millions of app opens in minutes). Almost every design choice comes from managing the gap between the two.

PatternWhere it appearsWhat it buysWhat it costs
Promise a percentile, then keep itLessons 1, 4, 12, 13Customer trust; one deadline for every downstream systemLonger shown times; complex models
Shed demand instead of adding supplyLessons 4, 6, 11, 16Stable delivery under peaks and rainLost orders, surge fees, reduced coverage
Fallback at every layerLessons 5, 6, 19The home screen survives dependency failuresTwo of everything; less accurate answers in failure
Cache by a discretised keyLessons 5, 7, 21Turns infinite key spaces into cacheable onesError at cell edges; tuning resolution
Optimise in small, bounded batchesLessons 2, 3, 10, 11Solver results within the decision intervalGlobal optimality; boundary effects
Wait on purposeLessons 2, 10Better batches, less idle rider timeSome orders wait longer for assignment
A log as the source of truthLessons 8, 15, 23Replayable replicas, CDC, durable pipelinesEventual consistency; retention must be right
Explore a little, alwaysLessons 20, 22, 26Models that notice changeA small, steady loss on the exploring share
Guard rails on elasticityLessons 16, 18Bounded bills and bounded retry stormsLess burst capacity when you might want it
General domain modelLessons 9, 23New business lines without forksHarder to learn; translation cost per business

Overlooked constraints, across the posts.

  • The real bottleneck is often physical. Riders, roads and kitchens cap throughput long before CPUs do. Software can only shape demand and use supply better.
  • Every layer needs its own failure plan. The posts repeat one habit: name the failure modes of each dependency, and build a cheaper fallback for each.
  • Measurement decides outcomes. Swiggy's biggest gains often came from defining the metric well: backlog in demand (Lesson 11), bumps in ETAs (Lesson 13), agreement in map quality (Lesson 7), extreme delays in promises (Lesson 12).

What Swiggy sacrificed overall. Simplicity and peak revenue. The platform carries fallbacks, backup services, two sets of models and many optimisers, which is a lot to maintain. And when supply is short it deliberately turns away orders rather than delivering them late. Swiggy pays in complexity and some lost orders to protect the promise.

Deep Dive: a dinner peak, end to end, in numbersShow

Setup (handbook's illustration). One large city at 8 pm: 40,000 app opens a minute, 4,000 orders a minute at peak, 25,000 riders logged in, average delivery 32 minutes.

Little's law. Orders in flight = arrival rate × time in system = 4,000 × 32 = 128,000 order-minutes per minute, or 128,000 active orders if each took the full 32 minutes of a rider's time. Riders spend only part of that on an order, say 22 minutes of rider time each. Then rider demand is 4,000 × 22 = 88,000 rider-minutes per minute, which needs 88,000 riders with batching factor 1. With 25,000 riders, that is impossible without batching and shorter trips. A batching factor of 1.5 and average rider time of 15 minutes per order brings it to 4,000 × 15 / 1.5 = 40,000. That is still too many. So serviceability must cut demand or lengthen promises: stress levels rise, long last-mile pairs vanish from the listing, surge appears.

Where it settles. If stress cuts orders to 2,500 a minute, need = 2,500 × 15 / 1.5 = 25,000 riders. Supply and demand meet, which is exactly what the stress FSM steers toward.

Read side. 40,000 opens a minute × 2,000 outlets = 80 million serviceability evaluations a minute, about 1.3 million a second, each needing a distance. At a 95 percent cache hit rate, 67,000 live route calculations a second remain, which needs a large routing fleet. At 99 percent, 13,000. Each point of hit rate is worth thousands of CPU cores, which is why Lesson 5's key design matters so much.

Cross-cutting: classic interview topics seen through Swiggy#

The reference material behind this handbook (the System Design Primer, Hello Interview's guides and the awesome-system-design list) covers several general topics that Swiggy's posts make concrete.

A cache for recent query results. The primer's query-cache exercise designs a key-value cache for the results of recent web searches. It assumes 10 million users and 10 billion queries a month, about 4,000 requests a second. Each entry is about 270 bytes (a 50-byte query, a 20-byte title and a 200-byte snippet). If every query were unique, that would be about 2.7 TB a month, so the cache must evict. The design:

  • A Query API normalises the query first: strip markup, split into terms, fix typos, normalise case and convert to boolean operators. Normalisation is what makes "Biryani " and "biryani" hit the same entry.
  • LRU eviction, built from a hash map (key to node) plus a doubly linked list (recency order), gives O(1) lookups and updates.
  • Cache-aside: check the cache; on a miss, query the backend and fill the cache.
  • Refresh when a page's content or rank changes, or when a TTL expires.

To scale beyond one machine there are three options: each node keeps its own cache (simple, but low hit rate); each node keeps a full copy (high memory cost); or the cache is sharded across nodes with consistent hashing, which is the best fit, because adding a node moves only a small share of keys. Swiggy's autocomplete (Lesson 21) is the same problem, keyed by prefix and city. See distributed caching and consistent hashing.

A distributed cache beside a search service. Hello Interview's post-search breakdown improves search latency by caching recent query results in a distributed cache such as Redis, without personalisation, with a TTL under one minute to match a one-minute freshness requirement. A better version also puts a CDN in front, using cache-control headers, so the most common queries return from the edge in tens of milliseconds instead of hundreds. Swiggy's catch is location: results depend on serviceability, so the cache key must include a geohash or locality, and stress changes must invalidate it. In practice that means short TTLs and caching the stable parts (text match candidates) separately from the volatile parts (serviceability and ETAs).

Timeline and search: the primer's Twitter design. The primer's Twitter exercise is a good contrast with Swiggy's feed:

  • Scale: 100 million active users, 500 million tweets a day, 250 billion reads a month (about 100,000 reads a second), 6,000 tweets a second, 60,000 fan-out deliveries a second and 4,000 searches a second. Each tweet with media averages about 10 KB, so about 150 TB of new content a month.
  • Posting: the write API stores the tweet in the author's timeline in SQL. A fan-out service looks up followers and pushes the tweet ID into each follower's home timeline list in a memory cache such as Redis. That is O(followers) per tweet. It also indexes the tweet for search, stores media in object storage and queues push notifications.
  • Reading the home timeline: read the list of IDs from memory in O(1), then multiget tweet details and user details from their services.
  • Search: the search API tokenises and normalises the query, scatter-gathers across a Lucene cluster, then merges, ranks and sorts.
  • Scaling: celebrities with millions of followers make fan-out slow. So their tweets are not fanned out; they are fetched at read time and merged into the timeline. Keep only a few hundred items per home timeline in memory, only for active users, rebuilding inactive users' timelines from the database. Keep a month of tweets in the tweet service. The SQL write path then needs federation, sharding, denormalisation and tuning, and some data moves to NoSQL.

Swiggy's listing feed is the opposite case. Nothing is fanned out on write, because the "followed set" (serviceable restaurants) depends on where the customer is right now and on fleet stress. The feed is computed on read, which is why serviceability is so heavily cached and parallelised. Kabootar (Lesson 23) is where Swiggy does fan-out: a campaign to millions of users goes through queues, like the primer's notification step. See scaling reads and real-time updates.

Cache architectures. Hello Interview's caching lesson describes four ways to place a cache:

  • Cache-aside (lazy loading) is the default: the app reads the cache, and on a miss reads the database and fills the cache. Only data that is actually requested gets cached.
  • Write-through writes to the cache and the database together. Reads are always warm, but the app now has a dual-write problem: if one write succeeds and the other fails, they disagree.
  • Write-behind writes to the cache and flushes to the database later. Writes are fast, but a cache crash loses data.
  • Read-through puts the cache in charge of loading from the database on a miss. A CDN is the familiar example.

Swiggy's distance cache (Lesson 5) is cache-aside with write-back on miss, guarded by memory marks. Its feature store (Lesson 17) is filled by bulk jobs, a form of cache warming. See caching strategies.

Cache stampede. When a hot key expires, many requests miss together and all hit the backend: a thundering herd. The fixes are request coalescing (single flight: one request recomputes, the others wait for its result) and cache warming (refresh hot keys before they expire). Warming helps only with TTL expiry, not with evictions or cold starts. Swiggy's Stop Write mark and fallback chain are a different kind of guard: they stop a cache problem from becoming a backend overload. See cache failure modes.

Why memory caches at all. The URL-shortener breakdown gives the numbers that justify Redis in front of a database: memory access is about 100 ns, an SSD read about 0.1 ms and a spinning disk about 10 ms. Memory handles millions of operations a second; an SSD about 100,000 IOPS; a hard disk 100 to 200. The concerns are always the same: invalidation, warm-up and eviction policy (usually LRU). Swiggy's sub-millisecond distance budget only works because the hot set lives in memory.

The distributed-systems toolkit. The awesome-system-design list groups the core building blocks of distributed systems and microservices. Each appears in Swiggy's posts:

  • Heartbeats and failure detection: the stress cluster rebalances localities when a node leaves (Lesson 6). See failure detection and gossip.
  • Service discovery: 400+ services need to find each other; the logistics tiers (Lesson 9) depend on it.
  • Consensus and leader election: Swiggy rejected a Raft-based store for geo (Lesson 8) because it is CP. See consensus.
  • Distributed locking: a rider must not get two batches at once (Lessons 3 and 10). See distributed locking.
  • Gossip: Ringpop, considered and rejected in Lesson 8, is a gossip-based membership library.
  • Circuit breakers: detecting blackouts and brownouts (Lesson 19). See resilience patterns.
  • Disaster recovery: AOF snapshots to S3 and Kafka replay (Lesson 8); a secondary distance cache cluster (Lesson 5). See disaster recovery.
  • Distributed tracing: with 130+ services on the order path, a trace ID across calls is the only way to see where 100 ms went. See observability.

How to answer a design problem, and which problems Swiggy helps with. The awesome-system-design list links a step-by-step answer method and a graded list of interview problems. Its problems that Swiggy's posts speak to directly include food delivery (like DoorDash), Uber-style ride matching, Yelp-style nearby search, Google Maps-style routing, a payment system, a notification service, autocomplete and a distributed cache. The handbook's interview framework walks the same steps. Here is a Swiggy-flavoured answer at each one:

StepSwiggy-flavoured answer
Functional requirementsBrowse serviceable restaurants; search; cart with a promised time; pay; assign and batch riders; live tracking; notifications
Non-functional requirementsListing under 200 ms P99 for 2,000 outlets; promises kept at a high percentile; graceful degradation under stress; payments exact
EstimatesAbout 100,000 listing calls a minute, 200 million distance pairs a minute; peak orders thousands a minute per big city; 4 to 5 hour rider sessions with pings every few seconds
APIListing and search over REST or gRPC with protobuf; tracking via polling or push; payment initiation with idempotency keys
Data modelJobs, tasks, legs and trips (Lesson 9); geo polygons in a geo store (Lesson 8); orders in MySQL or DynamoDB; CDC to a Delta Lake
High-level designServiceability aggregator, distance cache, stress cluster, logistics platform, zoned assignment solvers, Kafka, ML platform
Deep divesDistance caching keys; batching with time windows; stress FSM; ETA models and bump metrics; payment routing exploration
Wrap-upWhat is shed under peak; which components fall back; how retry storms and runaway autoscaling are bounded

When to Use It#

Study the Swiggy posts when:

  • You are designing a hyperlocal marketplace: food, grocery, pharmacy or parcel delivery, where supply is physical and demand is spiky.
  • You need a read path that computes per-user, per-location answers at very high volume, and you want worked examples of caching, parallel aggregation and fallbacks.
  • You face geo problems at scale: point-in-polygon, nearby search, road distance and map quality.
  • You are building optimisers that must finish within a time window: batching, assignment, rebalancing.
  • You want ML in production stories that include metrics, fallbacks and explainability, not just model choice.
  • You are preparing for interviews on food delivery, ride-hailing, nearby search, payments, notifications or autocomplete.

When NOT to Use It#

  • Purely digital products with elastic supply. If capacity is just servers, you can scale out instead of shedding demand. Many of Swiggy's choices (stress levels, surge, holding orders) would be needless complexity.
  • Global, multi-region systems. The posts are about operating within cities in one country. For cross-region replication and latency, look at the Netflix and Meta pages.
  • Small teams. Two of everything, many optimisers and an ML platform need many engineers. A small delivery startup should copy the ideas (percentile promises, fallbacks, geohash caches), not the full machinery.
  • Strong consistency everywhere. If your domain cannot accept stale reads, such as a trading ledger, see the Zerodha page instead.

How to Implement It#

  1. Write down the promise. Decide what you show the customer (a delivery time, an availability flag), at what percentile, and which systems will treat it as a deadline.
  2. List every input to the promise (geo, distance, capacity, predictions, pricing) and give each a freshness budget and an owner.
  3. Design the read path as a dependency graph with a top-level deadline. Run independent inputs in parallel; give each a timeout and a fallback.
  4. Discretise keys for caching. Use geohash or H3 cells for locations, at mixed resolution where density varies. Add TTLs, memory marks and a fallback when the cache is cold or down.
  5. Model capacity as states, not a number. A few stress levels with hysteresis, published by webhooks or pub/sub, are easier to act on than a raw ratio.
  6. Plan demand shedding. Decide what goes first under stress (long trips, low-value orders), and which lever (hiding, longer promises, surge) applies at which level.
  7. Bound optimisers by time. Partition the problem (zones), use heuristics with deadlines, and measure boundary losses.
  8. Make events the backbone. Kafka for service events, CDC for database changes, with retry budgets, exponential backoff and a wrapped client library.
  9. Put guard rails on elasticity: alarms and automatic caps for autoscaling databases, retry storms and bulk jobs.
  10. Measure with the right metric before tuning models: percentiles and extreme-delay rates, bump rates, backlog-aware demand, SRM checks for experiments.
# Serviceability read-path config (handbook's illustration)
serviceability:
  deadline_ms: 200
  geo_filter:
    index: geohash
    resolution: 6
    fallback: radial
    radial_km: 4
  distance:
    cache_key: geohash_pair
    resolution_dense: 8
    resolution_sparse: 7
    ttl_days: 14
    memory_high_water_pct: 80
    memory_stop_write_pct: 90
    on_miss: osm_bidirectional_astar
    on_error: haversine_x1_4
    failover_cluster: distance-cache-secondary
  stress:
    levels: [normal, s1, s2, s3]
    evaluate_every_s: 60
    max_last_mile_km: { normal: 7, s1: 6, s2: 4.5, s3: 3 }
  predictions:
    source: dsp
    timeout_ms: 40
    cache_ttl_s: 60
    fallback: locality_moving_avg_plus_lr
  backup_service: serviceability-lite

Technology choices.

NeedSwiggy choiceAlternativesWhen each fits
Geo store for polygons and pointsTile38 with Kafka-fed clonesPostGIS, Redis GEO, Elasticsearch geo, S2 or H3 librariesPostGIS for rich SQL and moderate update rates; Redis GEO for simple radius queries; libraries when you build your own store
Road distanceOSM with GraphHopper, Google for some pairsOSRM, Valhalla, commercial APIsCommercial for accuracy without map work; OSRM or GraphHopper for cost and two-wheeler profiles
Spatial indexing for analyticsH3 in SparkS2, geohash, PostGIS joinsH3 for uniform hexagon neighbours; geohash for simple prefixes; PostGIS for small data
Batching and assignmentHeuristics plus ILP per zone, GurobiOR-Tools, custom heuristicsCommercial solvers for speed on large ILPs; OR-Tools when licences matter
Event backboneKafkaPulsar, Kinesis, RabbitMQKafka for high-volume ordered logs; RabbitMQ for task queues with routing (as in Kabootar)
CDC to lakeBinlog and DynamoDB Streams to Delta LakeDebezium to Iceberg or Hudi, managed CDCDelta on Databricks; Iceberg for engine-neutral lakes; Hudi for upsert-heavy tables
Feature storeElastiCache Redis clusterDynamoDB, Feast with Redis, CassandraRedis for sub-millisecond reads; DynamoDB for less operations work; Cassandra for very large feature sets
Search and autocompleteOpenSearch with LTR pluginElasticsearch LTR, Vespa, SolrOpenSearch or Elasticsearch for familiar operations; Vespa for heavy in-engine ML ranking
ExperimentationIn-house XP with podsGrowthBook, Optimizely, StatsigBuy for standard A/B tests; build when you need switchbacks and marketplace designs
NotificationsKabootar on RabbitMQSNS, Firebase, managed CPaaSManaged services for small scale; an in-house router for many channels, priorities and campaigns

Trade-offs#

Choice Swiggy madeWhat it boughtWhat it cost
Promise a percentile, not the meanPromises kept for most ordersLonger shown times; some lost conversions
Shed demand under stressStable delivery quality at peaksFewer orders and less choice at the worst moments
Fallback at every layer, plus a backup serviceHome screen survives most failuresTwo of many things to build, test and keep in sync
Geohash-pair distance cache with mixed resolution200 million pairs a minute on sane hardwareError at cell edges; tuning and capacity marks
Zoned solversAssignment within the intervalLost cross-zone optimisations; at-risk edges
Masterless Tile38 clones over KafkaNo leader failover; high read availabilityEventual consistency; Kafka becomes critical
OSM over commercial mapsCost, two-wheeler accuracy, controlMust measure and fix map quality in-house
CDC to Delta LakeFresher data; over 20 percent replica savingsStreaming merge, schema and compaction complexity
One shared Kafka cluster for the order pathSimple operationsOne cluster's incident reached 18 services
Exploration in routing and rankingModels that notice changeSmall, steady loss on the exploring share
Logistic regression over trees for cardsExplainable routingGave up any small accuracy edge

Common Pitfalls#

  • Promising the average. Half of all orders will be late. Promise a percentile and measure extreme delays.
  • Caching on raw coordinates. Keys never repeat, and the cache only consumes memory. Discretise first.
  • Retrying at a fixed interval. Thousands of clients retrying every 100 ms is a flood. Use exponential backoff with jitter and retry budgets.
  • Trusting one remote model service. Keep a cheap statistical fallback in memory.
  • Letting autoscaling run unbounded. Put alarms and automatic caps on on-demand databases and bulk jobs.
  • Assigning greedily and instantly. Without holding and batching, riders travel more and wait more.
  • Standard A/B tests in a marketplace. Variants that share riders contaminate each other. Use switchbacks or geographic splits.
  • Ignoring client library versions. Shared infrastructure fails in different ways for different client versions. Wrap and track them.

Real-World Examples#

  • Uber: the closest parallel, with dispatch, geo indexing (H3 came from Uber), ETA models, surge pricing and experimentation for a two-sided marketplace.
  • Zerodha: another Indian company at very high scale, which makes the opposite bet on vertical scaling and self-hosting for strongly consistent financial data.
  • Discord: real-time fan-out and data-store migrations, a contrast to Swiggy's compute-on-read listing.
  • Netflix: resilience engineering, fallbacks and experimentation at global scale.
  • Stripe: payment correctness and idempotency, the other side of Swiggy's gateway routing.
  • AWS Builders' Library: backoff with jitter, load shedding and static stability, the general form of Lessons 6, 16 and 19.
  • Cloudflare and Meta: edge caching and cache-consistency lessons that apply to Swiggy's read path.
  • Case studies: food delivery, payment system, notification system and experimentation platform.

In the Interview#

Deep Dive: designing a small delivery app with Swiggy's lessonsShow

Problem. A new delivery service in one city: 1,500 restaurants, 300,000 monthly users, 30,000 orders a day, a dinner peak of 150 orders a minute, 1,500 riders at peak.

Estimates. If 10 users browse for every order, peak listing calls are about 1,500 a minute, 25 a second. Each sees about 600 nearby restaurants, so 15,000 distance pairs a second. A cache keyed by level-7 geohash pairs covers most of them; a single routing server (GraphHopper or OSRM with preprocessing) handles the misses. Rider demand at peak: 150 orders a minute × 18 rider-minutes per order = 2,700 rider-minutes a minute, against 1,500 riders. A batching factor of 1.3 brings it to about 2,080. That is still short, so stress levels and a smaller radius at peak are needed from day one.

Design.

  • Serviceability: one stateless service with an in-memory polygon index per city, a Redis distance cache, a stress level per zone computed every minute by one scheduled worker, and a simple ETA model (moving averages by zone and hour, plus a distance term) with the cart percentile at P80.
  • Orders and payments: PostgreSQL for orders, payments and tasks, with idempotency keys on payment calls and one gateway plus a backup. Add explore-exploit routing only when you have several gateways and enough volume.
  • Logistics: jobs and tasks from day one, even for food only. A greedy assignment every 30 seconds with a short hold for batching, and an ILP later.
  • Events: a managed Kafka or a Postgres outbox feeding a queue. CDC from Postgres to object storage for analytics.
  • Apps: a rider app with native location services and an offline action queue; tracking via polling every 10 seconds before investing in push.
  • Guard rails: exponential backoff with jitter in every client, per-call timeouts under a top-level deadline, billing alarms on managed databases.

What to postpone. Zoned solvers, Tile38 clones, OSM quality pipelines, multi-output deep ETA models and in-house experimentation platforms all pay off at Swiggy's scale. At one city, buy or simplify, and keep the interfaces (promise, stress levels, tasks) so the pieces can grow later.

Key Takeaways#

  • Swiggy's design centre is the gap between elastic demand and inelastic supply. Most choices either shape demand (serviceability, stress, surge) or use supply better (batching, zoning, supply shaping).
  • The promise is a contract. Promise a percentile, measure extreme delays and unnecessary ETA bumps, and let every downstream system use the same number.
  • Serviceability is a huge read path: about 200 million distance pairs a minute. It works through geohash indexes, geohash-pair caches at mixed resolution, a parallel dependency graph and a fallback at every step.
  • Optimisation must finish in time. Holding orders on purpose, inserting into frozen routes and partitioning by learned zones trade some optimality for decisions that land within the interval.
  • Logs as sources of truth (Kafka-fed geo clones, CDC to Delta Lake) give replayable, durable systems, at the price of eventual consistency and careful retention.
  • Reliability lessons are concrete: retry floods, client library bugs, runaway autoscaling bills and fixed latency budgets each have a specific, reusable fix.
  • ML in production needs exploration, fallbacks and explainability, as payment routing, feed ranking and the fallback ETA models show.