> ## Documentation Index
> Fetch the complete documentation index at: https://docs.livingsecurity.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 速率限制

> Living Security Public API 的請求額度、429 回應規範，以及如何依據 Retry-After 進行重試。

`/v1` API 會強制執行兩項相互獨立的請求額度。只要其中任一額度用盡，請求即會遭到拒絕。

| 額度 | 適用對象 |
| - | - |
| 每個 API 金鑰 | 從任何位址提交該金鑰的每一項請求 |
| 每個用戶端 IP | 來自該位址的每一項請求，無論是否已通過驗證 |

每個金鑰的額度會隨金鑰使用的位置而計算。每個 IP 的額度是未經驗證流量唯一適用的額度，同時也是已驗證流量的第二道上限。

<Note>
  速率限制會在驗證之前執行，因此使用無效或缺少憑證的請求，同樣會計入來源的額度。確切的數值額度由營運方設定，且可能變更；下方的回應規範則是可供您穩定依循的介面。
</Note>

請使用任一種 Basic 憑證格式進行驗證，請參閱
[快速入門](/zh-Hant/developers/v1/quickstart)（`apikey:secret` 或 `secret:`）。
請將 `BASE` 設定為貴組織所屬區域的主機，請參閱
[區域](/zh-Hant/developers/v1/regions)。

## 429 回應

當額度用盡時，API 會傳回 `429 Too Many Requests`，並附上 `Retry-After` 標頭（以秒為單位）以及標準的問題詳細資料（problem-details）內容：

```json 429 Too Many Requests theme={null}
{
  "type": "https://docs.livingsecurity.com/developers/v1/errors/rate_limited",
  "title": "Too Many Requests",
  "status": 429,
  "detail": "Rate limit exceeded. Retry after the Retry-After interval.",
  "code": "rate_limited",
  "request_id": "req_...",
  "doc_url": "https://docs.livingsecurity.com/developers/v1/errors/rate_limited",
  "retryable": true
}
```

回應不會說明是哪一項額度用盡。請以相同方式處理每個 `429`：先等待，再重試。

## 處理 429 回應

<Steps>
  <Step title="遵循 Retry-After">
    重試前，請至少等待 `Retry-After` 標頭中所指定的秒數。過早重試只會再次消耗額度，而這些請求仍會遭到拒絕。
  </Step>

  <Step title="重複發生時以指數方式退避">
    若重試再次遭到拒絕，請增加退避時間並加入隨機抖動（jitter），以免平行執行的工作程序同步重試。切勿為了配合本機上限而縮短伺服器指定的 `Retry-After`。若伺服器要求的等待時間超出您的重試額度所允許的範圍，請停止重試，並將該工作排程於稍後執行。
  </Step>

  <Step title="平緩您的請求速率">
    請優先採用穩定的請求速率，而非突發流量。進行大量讀取時，請使用最大的分頁大小（`limit=500`），以較少的請求涵蓋整個集合，請參閱
    [分頁](/zh-Hant/developers/v1/pagination)。當多個清單走訪作業平行執行時（例如 Power BI 資料表），請維持適度的並行量並遵循
    `Retry-After`，以免暫時性的 429 導致整個重新整理失敗。
  </Step>
</Steps>

此範例僅針對 **GET** 請求重試 `429` 回應，最多嘗試五次，且每次嘗試之間最多等待 60 秒。遇到其他錯誤時會立即停止。網路逾時會向上傳遞給呼叫端。請依據您的工作負載設定逾時與重試額度。`requests` 會將讀取逾時解讀為接收資料時的最長閒置時間，而非整體期限。

請從您的密碼管理工具載入 `LIVING_SECURITY_API_KEY`。執行此範例之前，請先安裝 `requests`。
請呼叫 `get_with_retry("/organization")` 以使用此範例。

```python Python theme={null}
import os
import random
import time
import requests

# US: BASE = "https://api.us-east-1.livingsecurity.ai/v1"
BASE = "https://api.eu-west-1.livingsecurity.ai/v1"
AUTH = ("apikey", os.environ["LIVING_SECURITY_API_KEY"])

def get_with_retry(path, params=None, max_attempts=5):
    if not 1 <= max_attempts <= 5:
        raise ValueError("max_attempts must be between 1 and 5")
    for attempt in range(max_attempts):
        response = requests.get(
            f"{BASE}{path}", auth=AUTH, params=params,
            headers={"Living-Security-Version": "2026-07-01"},
            timeout=(5, 30), allow_redirects=False,
        )
        if response.status_code != 429:
            response.raise_for_status()
            if not 200 <= response.status_code < 300:
                raise RuntimeError("Unexpected redirect; check your regional API URL")
            return response

        # The API returns Retry-After as a whole number of seconds.
        raw_wait = response.headers.get("Retry-After", "")
        request_id = response.headers.get("Request-Id", "unknown")
        response.close()
        if attempt == max_attempts - 1:
            raise RuntimeError(f"Retry budget exhausted; request_id={request_id}")
        if not raw_wait.isascii() or not raw_wait.isdigit() or len(raw_wait) > 6:
            raise RuntimeError(f"Invalid Retry-After; request_id={request_id}")

        wait = max(int(raw_wait), min(2 ** attempt, 30))
        delay = wait + random.uniform(0, 1)
        if delay > 60:
            raise RuntimeError(f"Retry-After exceeds wait budget; request_id={request_id}")
        time.sleep(delay)
```

請勿將此迴圈複製到寫入作業周圍使用。寫入後發生逾時，可能表示伺服器已在連線失敗之前完成提交。僅當該作業的參考文件明確說明具備冪等性時，才可重複執行寫入，且必須保留相同的金鑰與內容。否則，請先核對資源狀態，再重新嘗試。

## 建議的重新整理排程

請依據您的金鑰額度與分頁大小來規劃重新整理頻率。對大型集合進行完整的歷史資料載入屬於一次性成本；在穩定狀態下的重新整理，建議採用增量時間範圍，使每次執行都能維持在額度之內並保有充裕餘裕。請務必明確設定
`limit=500`，預設值 25 會使請求數量倍增。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.