# Timeouts और Latency Budgets — API Gateway और Service Mesh

Source: https://www.geekswithgeeks.com/hi/api-gateway-service-mesh/z-timeouts

> हर hop पर स्पष्ट timeouts तय करें और chain भर में latency का budget बनाएँ।

## Timeout नहीं तो हमेशा इंतज़ार

धीमी dependency अक्सर मरी हुई से भी बुरी होती है, क्योंकि अनुरोध connections और threads रोके ढेर होते जाते हैं जब तक caller भी विफल न हो जाए: **cascading failure**। Gateway और हर client पर **स्पष्ट timeouts** (connect, read) तय करें और गहराई में जाते हुए उन्हें **छोटा** रखें: user-सामने का budget 2 सेकंड हो तो gateway 1.8 s, service 1.5 s और उसकी database call 1 s दे सकती है, ताकि भीतरी परतें बाहरी के timeout से पहले हार मान लें। कुल को **latency budget** में शामिल करें: हर hop का सामान्य समय जोड़ें और देखें कि समय कहाँ जाता है।

## जल्दी विफल हों, सुधरें, बोझ बाँटें

वितरित systems आंशिक और धीमे विफल होते हैं; proxies समय सीमाएँ, सावधान retries, circuit breakers और समझदार balancing जोड़ते हैं।

![चार साधन: timeout, retry, breaker, balance।](assets/figures/api-gateway-service-mesh/section-4-map.svg) — चित्र 4.1 — Timeout, retry, breaker और balance।

## Gateway में read timeout (config)

`slow` upstream को 3 सेकंड लगते हैं; gateway 1 सेकंड बाद हार मान लेता है। Gateway config का अंश।

```nginx
location /slow/ { proxy_read_timeout 1s; proxy_pass http://slow_up/; }
```

## Gateway इसे 1 सेकंड पर काट देता है, चलाकर

मैंने यह Docker में असली nginx 1.27 gateway पर चलाया, upstreams के रूप में छोटी Node.js services के साथ (पूरा setup केस स्टडी में)। अनुरोध पूरे 3 सेकंड इंतज़ार करने की जगह लगभग 1 सेकंड बाद `504 Gateway Timeout` लौटाता है।

```bash
GET /slow/x
```

Output:

```
504 1s
```

## Latency budget, चलाकर

मैंने यह सादा-Python मॉडल चलाया। चार hops मिलकर 113 ms होते हैं, और सबसे धीमा (payments, 60 ms) कुल का 53% है, इसलिए वहीं अनुकूलन सबसे ज़्यादा मदद करता है।

```python
import hashlib, bisect, math, random

hops = {"gateway": 5, "auth": 8, "orders": 40, "payments": 60}
print(sum(hops.values()), "ms total;", round(100 * hops["payments"] / sum(hops.values())), "% in the slowest hop")

```

Output:

```
113 ms total; 53 % in the slowest hop
```

**Quiz:** भीतरी timeouts बाहरी से छोटे क्यों होने चाहिए?

- [ ] छोटा हमेशा ज़्यादा सटीक होता है
- [x] भीतरी calls बाहरी caller के timeout से पहले हार मानकर रिपोर्ट करती हैं
- [ ] यह सिर्फ़ bandwidth बचाता है
- [ ] HTTP में यह ज़रूरी है

*Answer:* भीतरी calls बाहरी caller के timeout से पहले हार मानकर रिपोर्ट करती हैं. वरना बाहरी परतें timeout हो जाती हैं जबकि भीतरी काम बेकार चलता रहता है।
