본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

AI 사용량 제한 알림

원문 보기 위키 갱신

AI 사용량 제한 알림 (AI Rate Limit Alerts)

이 튜토리얼은 LLM 쿼터가 토큰 기준으로 측정되다 보니 예산이 다 소진된 후에야 HTTP 429가 도착하는 문제를 다뤄요. AI Rate Limiting Advanced 정책은 남은 토큰과 한도 헤더를 제공하지만 80% 알림 기능은 없어서, post-function Policy가 Kong Konnect 데이터 플레인에서 이 헤더를 읽어 80% 사용 시점에 DECK_WEBHOOK_URL로 POST 요청을 보내요. 완성하면 80% 시점에는 여전히 200을 반환하면서 외부 채널에 알리고, 쿼터가 실제로 소진됐을 때만 429를 돌려주는 /ai-rate-limit-alerts 채팅 엔드포인트를 갖게 돼요

출처: 문서

본문

개요

LLM 할당량은 요청 수가 아니라 토큰으로 측정돼요. 그래서 HTTP 429는 예산이 이미 소진된 뒤에 도착하는 경우가 많아요. AI Rate Limiting Advanced는 remaining과 limit 헤더를 기록하지만, 80% 알림 필드는 내장돼 있지 않아요. post-function Policy가 Kong Konnect 데이터 플레인에서 이 헤더들을 읽고, 80%를 사용한 시점에 DECK_WEBHOOK_URL로 POST 요청을 보내요. 이 튜토리얼을 마치면 80% 시점에도 200을 반환하면서 외부 채널에 알리고, 할당량이 소진된 후에야 429를 반환하는 /ai-rate-limit-alerts 채팅 엔드포인트를 갖게 돼요.

사전 준비

Kong Konnect

이 튜토리얼은 Kong Konnect를 사용해요. AI Gateway 퀵스타트 스크립트는 레시피 스코프의 AI Gateway와 로컬 데이터 플레인을 프로비저닝해요. 실행 가능한 데모는 post-function Policy를 사용해 DECK_WEBHOOK_URL로 알림을 보내요.

  1. Konnect PAT 페이지를 열고 Generate Token을 선택해서 새 개인 액세스 토큰을 만드세요.

  2. 토큰을 내보내세요. 이 토큰은 나중에 kongctl 명령에서 다시 사용돼요:

    export KONNECT_TOKEN='YOUR_KONNECT_PAT'
    
  3. webhook.site에서 고유한 URL을 만들어 내보내세요. post-function Policy가 알림을 보낼 때 데이터 플레인이 이 값을 읽어요:

    export DECK_WEBHOOK_URL='https://webhook.site/YOUR-UUID'
    
  4. 레시피 스코프 AI Gateway 이름을 설정하고 퀵스타트 스크립트를 실행하세요. KONG_UNTRUSTED_LUA=on 덕분에 post-function Policy가 resty.http를 호출할 수 있어요. -e DECK_WEBHOOK_URL은 컨테이너에 웹훅 URL을 설정하고, KONG_NGINX_MAIN_ENV=DECK_WEBHOOK_URL은 이 값을 nginx 워커에 노출해서 post-function 안에서 os.getenv가 동작하게 해줘요:

    export KONNECT_CONTROL_PLANE_NAME='ai-rate-limit-alerts-recipe'
    curl -Ls https://get.konghq.com/ai | bash -s -- -k $KONNECT_TOKEN \
      -e KONG_UNTRUSTED_LUA=on \
      -e DECK_WEBHOOK_URL \
      -e KONG_NGINX_MAIN_ENV=DECK_WEBHOOK_URL
    

    이 명령은 ai-rate-limit-alerts-recipe라는 이름의 AI Gateway와 여기에 연결된 로컬 데이터 플레인을 프로비저닝하고, AI_GATEWAY_ID를 포함해 나머지 세션 변수를 위한 export 라인을 출력해요. 안내가 뜨면 이 내용을 셸에 붙여 넣으세요.

kongctl

이 튜토리얼은 AI Gateway 설정을 관리하기 위해 kongctl을 사용해요.

  1. developer.konghq.com/kongctl에서 kongctl을 설치하세요.

  2. 제대로 설치됐는지 확인하세요:

    kongctl version
    

OpenAI

이 튜토리얼은 OpenAI를 사용해요:

  1. OpenAI 계정을 만드세요.

  2. API 키를 발급받으세요.

  3. API 키를 환경 변수로 내보내세요:

    export DECK_OPENAI_TOKEN='Bearer sk-YOUR-KEY'
    

Python 3.11+

데모 스크립트에는 Python 3.11 이상이 필요해요. 격리된 환경을 준비하세요:

python3 -m venv .venv
source .venv/bin/activate
pip install 'openai>=1.0.0'

문제점

REST 레이트 리밋은 보통 클라이언트가 상한을 초과할 때까지 기다렸다가 429를 반환해요. LLM 트래픽에는 이 방식이 너무 늦어요:

  • 토큰 소비는 고르지 않아요. 짧은 인사말과 긴 RAG 프롬프트가 둘 다 HTTP 요청 하나로 계산돼요. 실제로 중요한 단위는 토큰인데, 클라이언트는 요청 수만으로 이를 예측할 수 없어요.
  • 429는 하드 스톱이에요. 운영과 재무 팀은 호출자가 실패하기 전에 할당량을 올리거나 부하를 줄일 수 있도록 "상한에 근접했다"는 신호를 원해요.
  • 앱별 헤더 폴링은 확장성이 없어요. AI Rate Limiting Advanced Policy는 remaining과 limit 헤더를 노출할 수 있어요. 하지만 모든 클라이언트가 이 헤더를 읽어야 하고, 모든 언어 스택이 같은 임계값 로직을 복제해야 해요.
  • 토큰 윈도우에는 조기 경보 필드가 내장돼 있지 않아요. 이 Policy는 하드 캡을 강제하고 remaining/limit 헤더를 내보낼 수 있지만, 80% 사용 시점에 외부 채널로 POST를 보내지는 않아요.

해결 방법

Kong은 채팅이 반환된 후에 이미 X-AI-RateLimit-Remaining-*과 X-AI-RateLimit-Limit-*을 기록해요. post-function AI Policy는 응답 본문이 끝난 뒤 이 헤더들을 읽고 (limit - remaining) / limit을 계산해요. 80% 시점에는 ngx.timer.at을 통해 resty.http로 DECK_WEBHOOK_URL에 POST 요청을 보내요. post-function이 없으면 80% 신호는 없어요.

 
sequenceDiagram
    autonumber
    participant C as Client
    participant DP as Kong AI Gateway
    participant LLM as OpenAI
    participant WH as webhook URL

    C->>DP: chat completions (apikey)
    Note over DP: key-auth Auth Strategy, then token window Policy
    alt quota remaining
        DP->>LLM: AI Model + Provider
        LLM-->>DP: 200 plus token usage
        Note over DP: post-function POST if used/limit >= 0.8
        DP->>WH: webhook POST (Konnect path)
        DP-->>C: 200
    else quota exhausted
        DP-->>C: 429
    end
  

key-auth Auth Strategy

역할: 레이트 리밋 파티션을 위해 apikey 헤더를 Consumer에 매핑해요.

ai-rate-limiting-advanced Policy

역할: Consumer별로 total_tokens를 집계하고, remaining과 limit 헤더를 설정하고, 윈도우가 비었을 때 429를 반환해요.

post-function Policy

역할: 이 헤더들로 80%를 계산하고, DECK_WEBHOOK_URL 웹훅으로 POST 요청을 보내요.

AI Model + Provider

역할: OpenAI 자격 증명을 주입하고 /ai-rate-limit-alerts를 프록시해요.

동작 방식

  1. 클라이언트가 apikey와 함께 /ai-rate-limit-alerts를 호출해요.
  2. key-auth AI Auth Strategy가 이 키를 Consumer에 매핑해요.
  3. ai-rate-limiting-advanced Policy가 해당 Consumer의 total_tokens를 집계하고 remaining과 limit 헤더를 기록해요. 윈도우가 비었으면 Kong은 429를 반환하고 중단해요.
  4. 채팅이 성공하면 AI Model이 OpenAI를 프록시해요.
  5. post-function Policy가 body_filter에서 실행되어 사용률을 계산하고, 80% 시점에 DECK_WEBHOOK_URL로 웹훅 POST를 예약해요. 호출자는 여전히 200을 받아요.

Key Auth: 할당량을 위한 Consumer 식별

key-auth AI Auth Strategy가 호출자를 식별해서 AI Rate Limiting Advanced가 Consumer별로 파티션할 수 있게 해줘요. 데모 키는 demo-api-key예요. 프로덕션에서는 애플리케이션마다 키를 하나씩 사용해야 해요.

설정 세부 사항

ai_gateway_auth_strategies:
- type: key-auth
  config:
    key_names:
      - apikey
    hide_credentials: true

{:.no-copy-code}

**key_names**는 클라이언트가 보내는 요청 헤더예요.
**hide_credentials**는 요청이 OpenAI에 도달하기 전에 키를 제거해요.

AI Rate Limiting Advanced: 토큰 윈도우와 헤더

ai-rate-limiting-advanced Policy는 Consumer별로 total_tokens를 집계해요. post-function이 remaining과 limit을 읽을 수 있도록 **hide_client_headers**를 false로 설정하세요. 50토큰 / 60초 윈도우는 작아서 데모가 빠르게 80%에 도달해요. AI Gateway 2.0에서는 윈도우가 config.policies[] 아래에 위치하고, identifier는 최상위 레벨에 둬요.

설정 세부 사항

ai_gateway_policies:
- type: ai-rate-limiting-advanced
  config:
    strategy: local
    identifier: consumer
    tokens_count_strategy: total_tokens
    hide_client_headers: false
    policies:
      - window_type: fixed
        limits:
          - limit: 50
            window_size: 60

{:.no-copy-code}

데이터 플레인이 둘 이상에서 카운터를 공유할 때는 strategy: redis를 사용하세요.

Post-function: 80% 신호

post-function Policy는 body_filter(eof)에서 실행돼요. total_tokens 헤더가 생긴 뒤 X-AI-RateLimit-Remaining-*과 X-AI-RateLimit-Limit-*(접미사는 모드에 따라 달라요)을 스캔해요. 80%를 사용한 시점에는 ngx.timer.at으로 resty.http를 예약하고(필터 페이즈에서는 cosockets을 사용할 수 없어요) DECK_WEBHOOK_URL로 POST 요청을 보내요.

**threshold = 80**은 사용률 퍼센트 값이에요. **dict:add(..., 1, 60)**은 같은 알림이 60초 동안 반복되지 않게 막아요. resty.http에는 KONG_UNTRUSTED_LUA=on이 필요해요. 데이터 플레인에도 워커가 DECK_WEBHOOK_URL을 읽을 수 있도록 KONG_NGINX_MAIN_ENV=DECK_WEBHOOK_URL이 필요해요.

AI Model: 채팅 프록시

AI Model은 Provider를 통해 OpenAI 키를 주입하고 /ai-rate-limit-alerts에서 채팅을 프록시해요.

프로덕션에서는 환경 변수 대신 {vault://backend/key} 참조를 사용해 자격 증명을 Kong Vaults에 저장하세요.

웹훅 본문에는 시크릿, 프롬프트, 전체 메시지를 담아 보내지 마세요.

Kong 구성 적용하기

다음 구성은 AI Model Provider, key-auth AI Auth Strategy와 Consumer, ai-rate-limiting-advanced Policy, 80% 웹훅을 위한 post-function Policy, 그리고 /ai-rate-limit-alerts에 하나의 AI Model을 만들어요. 모든 리소스는 kongctl 네임스페이스를 사용해 스코프가 지정돼요. 연합 구성 관리에 대해 더 자세히 알아보려면 kongctl 문서를 확인하세요.

먼저 퀵스타트 AI Gateway를 kongctl 네임스페이스로 adopt하세요. 그래야 이어지는 apply 명령이 이를 관리할 수 있어요.

kongctl adopt ai-gateway "${KONNECT_CONTROL_PLANE_NAME}" \
  --namespace "${KONNECT_CONTROL_PLANE_NAME}" \
  --pat "${KONNECT_TOKEN}"

adopt하면 AI Gateway에 KONGCTL-namespace 라벨이 찍혀요.

데모 Consumer의 API 키와 채팅 모델을 내보내세요. KONNECT_CONTROL_PLANE_NAME, KONNECT_TOKEN, DECK_OPENAI_TOKEN, AI_GATEWAY_ID, DECK_WEBHOOK_URL은 Prerequisites에서 이미 설정돼 있어요.

export DECK_CONSUMER_API_KEY='demo-api-key'
export DECK_CHAT_MODEL='gpt-4o-mini'

Kong 구성을 적용하세요:

cat <<'EOF' > kong-recipe.yaml
_defaults:
  kongctl:
    namespace: ai-rate-limit-alerts-recipe
ai_gateway_model_providers:
- ref: ai-rate-limit-alerts-provider
  ai_gateway: !lookup {id: !env 'AI_GATEWAY_ID'}
  name: ai-rate-limit-alerts-provider
  display_name: ai-rate-limit-alerts
  type: openai
  config:
    auth:
      type: basic
      headers:
      - name: Authorization
        value: !secret {source: !env 'DECK_OPENAI_TOKEN'}
ai_gateway_auth_strategies:
- ref: ai-rate-limit-alerts-auth
  ai_gateway: !lookup {id: !env 'AI_GATEWAY_ID'}
  name: ai-rate-limit-alerts-auth
  display_name: ai-rate-limit-alerts key auth
  type: key-auth
  config:
    key_names:
    - apikey
    hide_credentials: true
ai_gateway_consumers:
- ref: ai-rate-limit-alerts-consumer
  ai_gateway: !lookup {id: !env 'AI_GATEWAY_ID'}
  name: ai-rate-limit-alerts-consumer
  display_name: ai-rate-limit-alerts demo consumer
  type: api-key
  credentials:
  - ref: ai-rate-limit-alerts-credential
    name: ai-rate-limit-alerts-credential
    display_name: ai-rate-limit-alerts demo API key
    type: api-key
    api_key: !secret {source: !env 'DECK_CONSUMER_API_KEY'}
ai_gateway_policies:
- ref: ai-rate-limit-alerts-rla
  ai_gateway: !lookup {id: !env 'AI_GATEWAY_ID'}
  name: ai-rate-limit-alerts-rla
  display_name: ai-rate-limit-alerts token window
  type: ai-rate-limiting-advanced
  config:
    strategy: local
    identifier: consumer
    tokens_count_strategy: total_tokens
    hide_client_headers: false
    policies:
    - window_type: fixed
      limits:
      - limit: 50
        window_size: 60
- ref: ai-rate-limit-alerts-notify
  ai_gateway: !lookup {id: !env 'AI_GATEWAY_ID'}
  name: ai-rate-limit-alerts-notify
  display_name: ai-rate-limit-alerts 80% webhook
  type: post-function
  config:
    body_filter:
    - "if not ngx.arg[2] then\n  return\nend\nlocal rem, lim\nlocal headers = kong.response.get_headers()\
      \ or {}\nfor name, value in pairs(headers) do\n  local lower = string.lower(name)\n\
      \  if lower:find(\"x-ai-ratelimit-remaining-\", 1, true)\n     and not lower:find(\"\
      reset\", 1, true)\n     and not lower:find(\"retry\", 1, true) then\n    rem\
      \ = tonumber(value)\n  elseif lower:find(\"x-ai-ratelimit-limit-\", 1, true)\n\
      \     and not lower:find(\"reset\", 1, true)\n     and not lower:find(\"retry\"\
      , 1, true) then\n    lim = tonumber(value)\n  end\nend\nif not rem or not lim\
      \ or lim <= 0 then\n  return\nend\nlocal threshold = 80\nif (lim - rem) / lim\
      \ * 100 < threshold then\n  return\nend\nlocal consumer = kong.client.get_consumer()\
      \ or {}\nlocal id = consumer.id or kong.client.get_forwarded_ip() or \"anon\"\
      \nlocal dict = ngx.shared.kong\nif dict then\n  local added = dict:add(\"ai-rate-alert:\"\
      \ .. id, 1, 60)\n  if not added then\n    return\n  end\nend\nlocal url = os.getenv(\"\
      DECK_WEBHOOK_URL\")\nif not url or url == \"\" then\n  return\nend\nlocal username\
      \ = consumer.username or \"unknown\"\nlocal ok, err = ngx.timer.at(0, function(premature)\n\
      \  if premature then\n    return\n  end\n  local http = require(\"resty.http\"\
      )\n  local cjson = require(\"cjson.safe\")\n  local httpc = http.new()\n  httpc:set_timeout(3000)\n\
      \  httpc:request_uri(url, {\n    method = \"POST\",\n    body = cjson.encode({\n\
      \      text = string.format(\n        \"%s reached %s%% of the token quota.\
      \ %s tokens remaining.\",\n        username,\n        tostring(threshold),\n\
      \        tostring(rem)\n      ),\n      username = username,\n      remaining\
      \ = rem,\n      limit = lim,\n      rate = lim - rem,\n      threshold = threshold,\n\
      \      window = \"minute\",\n    }),\n    headers = { [\"Content-Type\"] = \"\
      application/json\" },\n    ssl_verify = true,\n  })\nend)\nif not ok then\n\
      \  kong.log.err(\"ai-rate-alert timer: \", err)\nend\n"
ai_gateway_models:
- ref: ai-rate-limit-alerts-model
  ai_gateway: !lookup {id: !env 'AI_GATEWAY_ID'}
  name: ai-rate-limit-alerts-model
  display_name: ai-rate-limit-alerts
  type: model
  formats:
  - type: openai
  capabilities:
  - generate
  access:
    auth_strategies:
    - ai-rate-limit-alerts-auth
  policies:
  - ai-rate-limit-alerts-rla
  - ai-rate-limit-alerts-notify
  config:
    max_request_body_size: 10485760
    response_streaming: allow
    logging:
      payloads: true
    route:
      paths:
      - /ai-rate-limit-alerts
      protocols:
      - http
      - https
      methods:
      - POST
      - OPTIONS
      strip_path: true
  targets:
  - name: !env 'DECK_CHAT_MODEL'
    provider: ai-rate-limit-alerts-provider
    config:
      type: openai
EOF
kongctl apply -f kong-recipe.yaml -o text --auto-approve --pat "${KONNECT_TOKEN}"

rm -f kong-recipe.yaml

{: data-test-step="block" .collapsible }

직접 사용해 보기

데모는 50토큰 윈도우가 비워질 때까지 max_tokens=1로 짧은 hi 채팅을 보내요. X-AI-RateLimit-Remaining-* 값이 떨어지는 걸 지켜보고, 80% 시점에 웹훅이 POST를 받았는지 확인하세요. 할당량이 소진되고 나면 Kong은 429를 반환해요.

OpenAI SDK는 api_key를 Authorization: Bearer로 보내요. 이 데모는 대신 default_headers={"apikey": ...}를 사용해요. 자세한 내용은 Key Auth로 OpenAI SDK 클라이언트 인증하기를 참고하세요.

데모 스크립트를 만드세요:

cat <<'EOF' > demo.py
"""AI rate limit early-alert demo.

Sends short chat completions through Kong until the Consumer uses 80% of a
50-token / 60-second window. Kong should POST a JSON alert to DECK_WEBHOOK_URL
at that threshold, then return HTTP 429 after the quota is exhausted.

Expected output:
  - Early requests -> 200, remaining headers well above 20%
  - At 80% used    -> 200, webhook inbox grows
  - After the quota -> 429

Run:
  export PROXY_URL=http://localhost:8000
  export DECK_WEBHOOK_URL=https://webhook.site/YOUR-UUID
  python demo.py
"""

from __future__ import annotations

import json
import os
import sys
import time
import urllib.error
import urllib.parse
import urllib.request

from openai import APIStatusError, OpenAI

PROXY_URL = os.getenv("PROXY_URL", "http://localhost:8000")
API_KEY = "demo-api-key"
WEBHOOK_URL = os.getenv("DECK_WEBHOOK_URL", "")
LIMIT = 50
THRESHOLD_PCT = 80

_USE_COLOR = sys.stdout.isatty() and "NO_COLOR" not in os.environ


def _c(code: str, s: str) -> str:
    return f"\033[{code}m{s}\033[0m" if _USE_COLOR else s


def BOLD(s: str) -> str:
    return _c("1", s)


def DIM(s: str) -> str:
    return _c("2", s)


def GREEN(s: str) -> str:
    return _c("32", s)


def RED(s: str) -> str:
    return _c("31", s)


def YELLOW(s: str) -> str:
    return _c("33", s)


def BLUE(s: str) -> str:
    return _c("34", s)


def remaining_from(headers: dict[str, str]) -> tuple[int | None, int | None]:
    rem = lim = None
    for raw_name, value in headers.items():
        name = raw_name.lower()
        if name.startswith("x-ai-ratelimit-remaining-") and "reset" not in name and "retry" not in name:
            rem = int(float(value))
        elif name.startswith("x-ai-ratelimit-limit-") and "reset" not in name and "retry" not in name:
            lim = int(float(value))
    return rem, lim


def webhook_token(url: str) -> str:
    path = urllib.parse.urlparse(url).path.strip("/")
    return path.split("/")[0] if path else ""


def webhook_count(token: str) -> int:
    if not token:
        return 0
    req = urllib.request.Request(
        f"https://webhook.site/token/{token}/requests?sorting=newest&per_page=20",
        headers={"Accept": "application/json"},
    )
    try:
        with urllib.request.urlopen(req, timeout=10) as resp:
            body = json.load(resp)
    except (urllib.error.URLError, json.JSONDecodeError, TimeoutError):
        return 0
    return len(body.get("data") or [])


def make_client() -> OpenAI:
    return OpenAI(
        base_url=f"{PROXY_URL}/ai-rate-limit-alerts",
        api_key="unused",
        default_headers={"apikey": API_KEY},
    )


def main() -> int:
    if not WEBHOOK_URL:
        print(RED("Set DECK_WEBHOOK_URL to your webhook.site unique URL."))
        return 1

    client = make_client()
    token = webhook_token(WEBHOOK_URL)
    before = webhook_count(token)
    print(BOLD("[SETUP]"))
    print(f"  {DIM(f'proxy={PROXY_URL}/ai-rate-limit-alerts limit={LIMIT} threshold={THRESHOLD_PCT}%')}")
    print(f"  {DIM(f'webhook inbox before={before}')}")

    got_429 = False
    for i in range(1, 20):
        print(f"\n{BOLD('[REQUEST]')} chat {i}")
        try:
            raw = client.chat.completions.with_raw_response.create(
                model="gpt-4o-mini",
                messages=[{"role": "user", "content": "hi"}],
                max_tokens=1,
            )
            headers = {k.lower(): v for k, v in raw.headers.items()}
            rem, lim = remaining_from(headers)
            used = (lim - rem) if rem is not None and lim else None
            pct = int(used / lim * 100) if used is not None and lim else None
            rem_s = f"{rem}/{lim}" if rem is not None and lim is not None else "n/a"
            used_s = f"{pct}%" if pct is not None else "n/a"
            remaining_s = f"remaining={rem_s}"
            print(f"  {GREEN('200')} {BLUE(remaining_s)} {DIM('used=' + used_s)}")
            if pct is not None and pct >= THRESHOLD_PCT:
                print(f"  {YELLOW(f'THRESHOLD {THRESHOLD_PCT}% reached')}")
        except APIStatusError as err:
            print(f"  {RED(str(err.status_code))} {DIM(str(err.message)[:120])}")
            if err.status_code == 429:
                got_429 = True
                break

    hit = False
    after = before
    for _ in range(15):
        after = webhook_count(token)
        if after > before:
            hit = True
            break
        time.sleep(1)

    if hit:
        print(f"\n{GREEN('[WEBHOOK]')} inbox grew {before} -> {after}")
    else:
        print(f"\n{RED('[WEBHOOK]')} no new POST at {WEBHOOK_URL}")
        return 1

    if not got_429:
        print(RED("[FAIL] expected HTTP 429 after the token quota"))
        return 1

    print(f"\n{GREEN('[OK]')} early alert fired before the 429")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
EOF

{:.collapsible}

실행하세요:

export PROXY_URL=http://localhost:8000
python demo.py

출력 예시:

[SETUP]
  proxy=http://localhost:8000/ai-rate-limit-alerts limit=50 threshold=80%
  webhook inbox before=0

[REQUEST] chat 1
  200 remaining=42/50 used=16%

[REQUEST] chat 5
  200 remaining=10/50 used=80%
  THRESHOLD 80% reached

[REQUEST] chat 7
  429 API rate limit exceeded

[WEBHOOK] inbox grew 0 -> 1

[OK] early alert fired before the 429

{:.no-copy-code}

웹훅 본문 예시:

{
  "text": "demo-app reached 80% of the token quota. 10 tokens remaining.",
  "username": "demo-app",
  "remaining": 10,
  "limit": 50,
  "rate": 40,
  "threshold": 80,
  "window": "minute"
}

{:.no-copy-code}

정확한 remaining 값은 OpenAI가 hi에 대해 보고하는 토큰 수에 따라 달라져요. 스크립트는 used/limit가 80% 이상인 지점을 먼저 찾고, 이어서 HTTP 429를 찾아요.

어떤 일이 일어났나요

  1. Key Auth가 apikey: demo-api-key를 데모 Consumer에 매핑했어요.
  2. AI Rate Limiting Advanced가 total_tokens를 집계하고 remaining/limit 헤더를 업데이트했어요.
  3. Post-function이 80% 시점에 POST 요청을 한 번 보냈어요. 같은 60초 안의 이후 채팅은 스누즈돼요.
  4. 429는 윈도우가 비워진 후에야 도착했어요. 호출자는 80% 시점에는 여전히 200을 받았어요.

Konnect에서 살펴보기

Konnect을 열고 ai-rate-limit-alerts-recipe라는 이름의 AI Gateway를 찾아보세요. 이 레시피는 AI Model Provider 하나, /ai-rate-limit-alerts 경로의 AI Model 하나, key-auth AI Auth Strategy, ai-rate-limiting-advanced Policy, post-function Policy, 그리고 데모 API 키를 가진 Consumer를 만들었어요. 이 모든 리소스는 위에서 적용한 kongctl 네임스페이스로 스코프가 지정돼요.

모든 AI Gateway에 걸친 플랫폼 전체 트래픽 분석을 보려면 Konnect의 Observability L1 메뉴로 이동하세요.

변형 및 다음 단계

할당량을 올리세요. limits.limit과 window_size를 변경하거나 local threshold = 80을 수정해 보세요.

웹훅을 Slack이나 PagerDuty로 연결하세요. Slack Incoming Webhooks 형식에 맞게 text를 구성하거나, 본문을 PagerDuty Events API 형식으로 바꾸세요. 프롬프트나 API 키는 포함하지 마세요.

Redis를 사용하세요. 둘 이상의 데이터 플레인이 카운터를 공유할 때 필요해요. AI Rate Limiting Advanced 문서를 참고하세요.

비용 기반 제한과 결합하세요. LLM Cost Optimization 문서를 참고하세요.

정리

레시피의 kongctl 네임스페이스가 모든 리소스를 스코프로 묶고 있기 때문에, 이 정리 작업은 이 레시피의 설정만 제거해요. 로컬 Data Plane을 정리하고 Konnect에서 AI Gateway를 삭제하세요:

export KONNECT_CONTROL_PLANE_NAME='ai-rate-limit-alerts-recipe' && curl -Ls https://get.konghq.com/ai | bash -s -- -d -k $KONNECT_TOKEN

더 알아보기 (Learn more)

  • 토큰 기반 사용량 제한과 remaining, limit 헤더를 제공하는 핵심 정책의 설정 방법을 알아봐요 — AI Rate Limiting Advanced
  • 응답 헤더를 읽어 80% 시점에 웹훅 알림을 보내는 데 사용되는 정책을 살펴봐요 — post-function
  • 이 튜토리얼의 쿼터 식별에 쓰이는 key-auth 방식으로 OpenAI SDK 클라이언트를 인증하는 방법을 확인해요 — Authenticate OpenAI SDK clients with Key Auth
  • 토큰 사용량과 비용을 관리하는 관련 코북으로 LLM 비용 최적화 전략을 더 깊이 알아봐요 — LLM Cost Optimization
  • 이 튜토리얼에서 AI Gateway 구성을 관리하는 데 사용하는 kongctl 도구를 익혀요 — kongctl
  • 웹훅 URL 같은 민감한 값을 안전하게 참조하는 Kong Vaults 사용법을 알아봐요 — Kong Vaults