Data Structures & Algorithms in Zepto: A Technical Repor t
Executive Summar y
Zepto is I ndia's f astest- growing quick commerce platf orm delivering groceries in 10
minutes. Founded in 2021 by Aadit Palicha and Kaivalya Vohra, Zepto operates 1, 000+
dark stores across 10 cities with a $ 5.9B valuation. This repor t analyzes the data
structures and algorithms enabling Zepto's ultra- f ast deliver y promise.
Key Metrics: 10- min deliver y, ₹11, 110 crore revenue (150% YoY), 135, 000+ SKUs, <75s
order packing, 40% latency reduction with MongoDB
Tech Stack: MongoDB Atlas, Redis, Node.j s, Python, Kaf ka, TensorFlow
1. System Architecture
1.1 Quick Commerce Model
Order Flow:
Customer Dark Store Selection Picking (<75s)
Par tner Assignment Route Optimization 10- Min Deliver y
Dark Store Strategy:
● Micro- warehouses in 2- 3 km radius
● Strategic placement in high- demand areas
● 1, 000+ stores across metro cities
1.2 Technology Stack
● Database: MongoDB Atlas (migrated f rom PostgreSQL)
● Cache: Redis clusters
● Backend: Node.j s, Python, Java
● AI / ML: TensorFlowf or f orecasting
● Messaging: Apache Kaf ka
● Mobile: React Native
1.3 MongoDB Migration Benefits
● 40% latency reduction
● 6x traf fic handling capacity
● Faster f eature deployment
● Eliminated complex j oins
2. Hash Maps & Geospatial I ndexing
2.1 Dark Store Selection
DarkStoreRegistr y: HashMap<Geohash, List<DarkStore>>
Algorithm:
1. Calculate user geohash
2. Quer y nearby stores (500m grid)
3. Check inventor y: O(1) per store
4. Select min(distance + load)
Time: O(k) where k = 3- 5 nearby stores
Space: O(n) f or n stores
Response: <50ms
2.2 I nventor y Management
I nventor yCache: HashMap<(StoreI D, ProductI D), Stock>
Operations:
- Check stock: O(1)
- Update stock: O(1)
- Reser ve items: O(1) with locking
Concurrency:
LOCK Check stock Decrement COMMI T
Handles 1000+ concurrent orders per store
2.3 Product Catalog
Catalog: HashMap<Categor y, HashMap<ProductI D, Product>>
Product {
id, name, price,
darkStoreStock: HashMap<StoreI D, Quantity>
}
Lookup: O(1) f or categor y and product
Total: O(1) retrieval
3. Priority Queues & Order Processing
3.1 Multi- Priority Order Queue
OrderQueue: Array[ 5] of PriorityQueue
Priority Levels:
0: Express (8 min target)
1: Standard (10 min)
2: Bulk (12 min)
3: Scheduled
4: Lowpriority
I mplementation: Min- heap by (priority, timestamp)
Enqueue: O(log n)
Dequeue: O(log n)
Peek: O(1)
3.2 Order Picking Optimization
Bin Packing + TSP Greedy:
1. Group items by aisle: HashMap<Aisle, I tems>
2. Sor t aisles by layout
3. Generate picking sequence
Time: O(n log n) f or n items
Result: <75s average packing time
3.3 Deliver y Par tner Assignment
AvailablePar tners: MinHeap by (distance, rating)
Assignment:
1. Filter AVAI LABLE par tners
2. Calculate distances: O(k)
3. Pop min distance: O(log k)
4. Update status to BUSY
Time: O(k log k), k = 20- 50 par tners
Response: <2 seconds
4. Graph Algorithms & Route Optimization
4.1 Road Network Graph
RoadNetwork: Graph
Ver tices: I ntersections ( V ≈ 10K per city)
Edges: Roads with weights
Edge {
f rom, to, distance,
traf ficFactor: 1.0- 3.0 (real- time),
roadType: MAI N| LANE | HI GHWAY
}
Space: O(V + E), E ≈ 25K per city
4.2 Dij kstra's Algorithm
findFastestRoute(star t, destination):
distances = HashMap(ver tices ∞)
distances[ star t] = 0
pq = MinHeap([ (star t, 0)] )
while pq not empty:
(current, dist) = [Link]()
if current == destination:
return reconstructPath()
f or edge in [Link](current):
weight = [Link] * [Link] ficFactor
newDist = dist + weight
if newDist < distances[ [Link]] :
distances[ [Link]] = newDist
[Link](([Link], newDist))
Time: O(( V + E) log V)
Per f ormance: <200ms per route
4.3 Multi- Stop Optimization (TSP)
2- opt Heuristic:
1. I nitial route: Nearest neighbor
2. Swap edge pairs
3. Accept if distance decreases
Time: O(n² ) per iteration
Practical: 3- 4 orders per trip
4.4 Real- Time Traf fic
Traf ficCache: HashMap<EdgeI D, Traf ficFactor>
Update: Ever y 2 minutes f rom Google Maps API
Dynamic Rerouting: I f delay > 3 min, recalculate
5. Trees & Search Structures
5.1 Decision Tree f or Demand Forecasting
Features: Day, time, weather, events, histor y
Structure: Random Forest (100 trees)
Prediction: O(log n) tree depth
Result: 30% inventor y accuracy improvement
5.2 B- Tree Database I ndexing
MongoDB Orders Collection:
I ndex: (user_ id, timestamp)
Quer y: Recent orders
[Link].find({user_ id: X})
.sor t({timestamp: - 1})
.limit(20)
Time: O(log n + 20) ≈ O(log n)
Height: 3- 4 levels f or millions of records
5.3 Trie f or Product Search
ProductTrie: Autocomplete system
Search " Mil" :
1. Traverse: M I L
2. Collect all leaf products
3. Rank by popularity
4. Return top 10
Time: O(m + k) where m = quer y length, k = results
Space: O(ALPHABET_ SI ZE * N* M)
Response: <100ms
6. Caching Strategies
6.1 Multi- Level Cache
L1 (Caf f eine): Hot products, sessions
TTL: 60s, Size: 50MB
L2 (Redis): Catalog, inventor y, profiles
TTL: 300s, Size: 100GB
L3 (MongoDB): Source of truth
Cache Hit Ratio: 95%
6.2 Write- Through f or I nventor y
UpdateI nventor y(store, product, quantity):
[Link]({store, product}, {$ inc: {qty: - quantity}})
[Link](f " {store}:{product}" , newQty, ttl=300)
kaf [Link](" inventor [Link]" , {store, product, qty})
Consistency: Strong (synchronous)
Latency: <50ms
6.3 Cache I nvalidation
Event- Driven Pattern:
- Order I nventor y cache
- Price update Product cache
- Profile change User cache
Mechanism: Kaf ka pub- sub
Propagation: <500ms
7. Load Balancing & Scalability
7.1 Consistent Hashing
LoadBalancer: TreeMap<Hash, Ser ver>
Vir tual nodes: 150 per ser ver
getSer ver(userI D):
hash = hash(userI D)
return [Link] y(hash) ?: ring.first()
Benefits:
- Session af finity
- Minimal redistribution on add/ remove
- Even load distribution
Time: O(log n) f or n ser vers
7.2 Auto- Scaling (Kubernetes)
Triggers:
- CPU > 70%
- Memor y > 80%
- Queue > 1000
- Latency > 500ms
Policy:
I F 2+ metrics exceed f or 2 min:
Scale up 20% (cooldown: 5 min)
I F all metrics < 30% f or 10 min:
Scale down 20% (cooldown: 10 min)
Result: 6x traf fic handling
8. Security & Fraud Detection
8.1 Bloom Filter
BlockedUsers: BloomFilter
Size: 10M bits (1.25 MB)
Hash f unctions: 7
False positive: 0.01%
checkUser(userI D):
if [Link](userI D):
return [Link] y(userI D)
return ALLOWED
Time: O(1), Space: 92% savings
8.2 Token Bucket Rate Limiting
RateLimiter: HashMap<UserI D, TokenBucket>
TokenBucket {
capacity: 10 orders
refillRate: 1/ hour
}
checkLimit(userI D):
[Link]fill()
if [Link] >= 1:
[Link] - = 1
return ALLOW
return REJECT
Time: O(1)
8.3 Anomaly Detection
Suspicious Patterns:
- Multi- device, same account (score +30)
- Location j ump >50km in 10min (+40)
- Newuser, high value order (+20)
- Velocity >5 orders/ hour (+10)
I F score >= 50: BLOCK_ OR_ VERI FY
Time: O(1) with cached data
9. Real- Time Analytics
9.1 Time- Series Monitoring
TimeSeriesDB: I nf luxDB (Circular Buf f er)
Buf f er[ 1440] // 1- min resolution f or 24 hours
Metrics per store:
- Orders/ minute
- Picking time
- Deliver y success rate
- Customer ratings
Write: O(1)
Quer y: O(k) f or k time points
9.2 Stream Processing (Kaf ka)
Order Stream Topic " orders"
Consumers:
1. Analytics: Aggregate metrics
2. I nventor y: Update stock
3. Notifications: Send confirmations
4. Fraud: Check patterns
Processing:
f or order in stream:
minuteOrders[ currentMin] += 1
revenue[ currentMin] += [Link]
[Link]()
Latency: <100ms
Throughput: 10, 000+ orders/ sec
10. Per f ormance & Conclusion
10.1 Complexity Summar y
Operation Data Structure Time Per f orman
ce
Store selection Geohash O(k) <50ms
HashMap
I nventor y HashMap O(1) <10ms
check
Order packing TSP 2- opt O(n² ) <75s
Route finding Dij kstra O(( V+E)log <200ms
V)
Product Trie O(m+k) <100ms
search
Cache lookup Redis O(1) <5ms
Rate limiting Token Bucket O(1) <1ms
Fraud check Bloom Filter O(1) <5ms
10.2 Key Achievements
● Deliver y: 10 minutes consistently
● Order Processing: <5 seconds (order to assignment)
● Cache Hit Rate: 95%
● Database Latency: <150ms (p95)
● Uptime: 99.9%
● Packing Time: <75 seconds
10.3 Core I nsights
1. Hash Maps enable O(1) inventor y and geospatial lookups
2. Priority Queues manage order sequencing ef ficiently
3. Graph algorithms optimize deliver y routes in real- time
4. Trees power search, indexing, and demand f orecasting
5. Caching achieves 95% hit rate reducing DB load
6. Consistent hashing provides scalable load distribution
7. Bloom filters enable ef ficient f raud prevention
10.4 Success Factors
● MongoDB migration: 40% latency reduction, 6x capacity
● Dark store model: Hyperlocal inventor y reduces deliver y time
● AI f orecasting: 30% better inventor y accuracy
● Real- time optimization: Dynamic routing adapts to traf fic
● Microser vices: I ndependent scaling of components
10.5 I mpact
Zepto demonstrates howf undamental DSA implementations combined with modern
distributed systems enable revolutionar y quick commerce. The 10- minute deliver y
promise is powered by:
● O(1) lookups f or time- critical operations
● O(log n) database queries with proper indexing
● Graph algorithms f or optimal routing
● Multi- level caching f or per f ormance
● Real- time stream processing f or responsiveness
Result: Transf orming grocer y shopping in I ndia with technology- driven ultra- f ast
deliver y at scale.