Skip to content

Improve behavior when rate-limit is exhaused + add rate-limit visibility - #28

Merged
rkosegi merged 1 commit into
dNationCloud:mainfrom
danielthegray:add-rate-limit-interceptor
Nov 23, 2026
Merged

rkosegi merged 1 commit into
dNationCloud:mainfrom
danielthegray:add-rate-limit-interceptor

Conversation

@danielthegray

Copy link
Copy Markdown
Contributor

This commit adds retries with exponential backoff for API calls that hit the rate-limit.

It also adds a way for the caller to have visibility into the Rate-Limits, so the 429s do not necessarily come as a surprise. The RateLimitBuckets object is optional (old code will continue working as before) and can be provided only when visibility into the budget left in the rate-limit quota is desired.

Testing

I built this change into a local version of the Jenkins Hetzner Cloud plugin and it is working well (and enabling me to display a small widget showing the last-seen rate limit snapshot).

Concerning the existence of two separate buckets (one of the /actions endpoints, and one for the rest), this was verified experimentally by running the following scripts:

Rate limit testing script

#!/usr/bin/env bash
set -euo pipefail

# Usage: ./test-rate-limits.sh <API_TOKEN>
# Writes results to rate-limit-results.log

TOKEN="${1:?Usage: $0 <API_TOKEN>}"
API="https://api.hetzner.cloud/v1"
LOG="rate-limit-results.log"

auth="Authorization: Bearer $TOKEN"

: > "$LOG"

log() { echo "$1" | tee -a "$LOG"; }

# Extract rate limit headers from a curl response
# Writes: endpoint limit remaining reset
rate_headers() {
    local label="$1" code limit remaining reset
    code=$(echo "$RESP_HEADERS" | head -1 | awk '{print $2}')
    limit=$(echo "$RESP_HEADERS" | grep -i '^ratelimit-limit:' | awk '{print $2}' | tr -d '\r')
    remaining=$(echo "$RESP_HEADERS" | grep -i '^ratelimit-remaining:' | awk '{print $2}' | tr -d '\r')
    reset=$(echo "$RESP_HEADERS" | grep -i '^ratelimit-reset:' | awk '{print $2}' | tr -d '\r')
    log "  $label => HTTP $code | Limit: $limit | Remaining: $remaining | Reset: $reset"
}

do_get() {
    local label="$1" url="$2"
    RESP_HEADERS=$(curl -sS -D - -o /dev/null -H "$auth" "$url")
    rate_headers "$label"
}

log "=== Hetzner API Rate Limit Bucket Test ==="
log "Started: $(date -u '+%Y-%m-%d %H:%M:%S UTC')"
log ""

# ── Phase 1: Baseline from non-destructive endpoints ──
log "── Phase 1: Baseline reads ──"
do_get "GET /servers"        "$API/servers"
do_get "GET /ssh_keys"       "$API/ssh_keys"
do_get "GET /images?type=system&per_page=1" "$API/images?type=system&per_page=1"
log ""

# ── Phase 2: Find cheapest non-deprecated server type, then create ──
log "── Phase 2: Find cheapest server type and create ──"

SERVER_TYPE=$(curl -sS -H "$auth" "$API/server_types?per_page=50" \
    | python3 -c "
import sys, json
data = json.load(sys.stdin)
types = [t for t in data['server_types']
         if t.get('deprecation') is None and t.get('prices')]
types.sort(key=lambda t: float(t['prices'][0]['price_monthly']['gross']))
print(types[0]['name'])
")
log "  Using server type: $SERVER_TYPE"

CREATE_RESP=$(curl -sS -D /tmp/_hdr_create -H "$auth" \
    -H "Content-Type: application/json" \
    -d "{
        \"name\": \"ratelimit-test-tmp\",
        \"server_type\": \"$SERVER_TYPE\",
        \"image\": \"ubuntu-24.04\",
        \"location\": \"fsn1\",
        \"start_after_create\": false
    }" \
    "$API/servers")

RESP_HEADERS=$(cat /tmp/_hdr_create)
rate_headers "POST /servers (create)"

ACTION_ID=$(echo "$CREATE_RESP" | python3 -c "import sys,json; print(json.load(sys.stdin)['action']['id'])" 2>/dev/null || true)
SERVER_ID=$(echo "$CREATE_RESP" | python3 -c "import sys,json; print(json.load(sys.stdin)['server']['id'])" 2>/dev/null || true)

if [ -z "$ACTION_ID" ] || [ -z "$SERVER_ID" ]; then
    log "ERROR: Failed to create server. Response:"
    log "$CREATE_RESP"
    exit 1
fi
log "  Server ID: $SERVER_ID, Action ID: $ACTION_ID"
log ""

# ── Phase 3: Aggressively poll the action endpoint ──
log "── Phase 3: Poll GET /actions/$ACTION_ID (20 rapid calls) ──"
for i in $(seq 1 20); do
    do_get "GET /actions/$ACTION_ID  (#$i)" "$API/actions/$ACTION_ID"
    sleep 0.1
done
log ""

# ── Phase 4: Check general endpoint rate limit after action polling ──
log "── Phase 4: Read general endpoints after action polling ──"
do_get "GET /servers"        "$API/servers"
do_get "GET /ssh_keys"       "$API/ssh_keys"
do_get "GET /servers/$SERVER_ID" "$API/servers/$SERVER_ID"
log ""

# ── Phase 5: Poll server endpoint a few times for comparison ──
log "── Phase 5: Poll GET /servers/$SERVER_ID (10 rapid calls) ──"
for i in $(seq 1 10); do
    do_get "GET /servers/$SERVER_ID  (#$i)" "$API/servers/$SERVER_ID"
    sleep 0.1
done
log ""

# ── Phase 6: Check action endpoint after server polling ──
log "── Phase 6: Read action endpoint after server polling ──"
do_get "GET /actions/$ACTION_ID" "$API/actions/$ACTION_ID"
log ""

# ── Cleanup: Delete the test server ──
log "── Cleanup: Deleting server $SERVER_ID ──"
RESP_HEADERS=$(curl -sS -D - -o /dev/null -X DELETE -H "$auth" "$API/servers/$SERVER_ID")
rate_headers "DELETE /servers/$SERVER_ID"
rm -f /tmp/_hdr_create
log ""

log "── Summary ──"
log "If /actions has a separate bucket, its Limit and Remaining values"
log "will differ from the /servers calls above."
log "Done: $(date -u '+%Y-%m-%d %H:%M:%S UTC')"

Script checking if all of the /actions endpoints indeed share a single rate-limit bucket

#!/usr/bin/env bash
set -euo pipefail

# Usage: ./scan-action-buckets.sh <API_TOKEN>
# Checks whether all resource-scoped /actions endpoints share the 7200 bucket.

TOKEN="${1:?Usage: $0 <API_TOKEN>}"
API="https://api.hetzner.cloud/v1"
LOG="rate-limit-action-buckets.log"

auth="Authorization: Bearer $TOKEN"

: > "$LOG"

log() { echo "$1" | tee -a "$LOG"; }

scan() {
    local path="$1"
    local headers code limit remaining
    headers=$(curl -sS -D - -o /dev/null -H "$auth" "$API$path" 2>/dev/null)
    code=$(echo "$headers" | head -1 | awk '{print $2}')
    limit=$(echo "$headers" | grep -i '^ratelimit-limit:' | awk '{print $2}' | tr -d '\r')
    remaining=$(echo "$headers" | grep -i '^ratelimit-remaining:' | awk '{print $2}' | tr -d '\r')
    printf "  %-55s => HTTP %-3s | Limit: %-6s | Remaining: %s\n" \
        "GET $path" "$code" "$limit" "$remaining" | tee -a "$LOG"
}

# Fetch the first resource ID from a list endpoint, empty if none
first_id() {
    local path="$1" key="$2"
    curl -sS -H "$auth" "$API$path?per_page=1" 2>/dev/null \
        | python3 -c "
import sys, json
data = json.load(sys.stdin)
items = data.get('$key', [])
print(items[0]['id'] if items else '')
" 2>/dev/null || true
}

log "=== Hetzner API Action Bucket Scan ==="
log "Started: $(date -u '+%Y-%m-%d %H:%M:%S UTC')"
log ""

# First, record the general bucket baseline
log "── General bucket baseline ──"
scan "/servers"
sleep 0.2

# Record the actions bucket baseline
log ""
log "── Actions bucket baseline ──"
ACTION_ID=$(curl -sS -H "$auth" "$API/servers?per_page=1" 2>/dev/null \
    | python3 -c "
import sys, json
servers = json.load(sys.stdin).get('servers', [])
if servers:
    sid = servers[0]['id']
    import urllib.request
    req = urllib.request.Request('https://api.hetzner.cloud/v1/servers/' + str(sid) + '/actions?per_page=1&sort=id:desc')
    req.add_header('Authorization', 'Bearer $TOKEN')
    data = json.load(urllib.request.urlopen(req))
    actions = data.get('actions', [])
    if actions:
        print(actions[0]['id'])
    else:
        print('')
else:
    print('')
" 2>/dev/null || true)

if [ -n "$ACTION_ID" ]; then
    scan "/actions/$ACTION_ID"
    sleep 0.2
fi
log ""

# Resources that have /actions sub-endpoints
declare -A RESOURCES=(
    [servers]=servers
    [volumes]=volumes
    [load_balancers]=load_balancers
    [floating_ips]=floating_ips
    [firewalls]=firewalls
    [images]=images
    [networks]=networks
    [certificates]=certificates
    [primary_ips]=primary_ips
)

log "── Resource-scoped action endpoints ──"
log ""

for resource in "${!RESOURCES[@]}"; do
    key="${RESOURCES[$resource]}"
    id=$(first_id "/$resource" "$key")
    if [ -n "$id" ]; then
        scan "/$resource/$id/actions"
    else
        printf "  %-55s => (no resources found, skipped)\n" "GET /$resource/{id}/actions" | tee -a "$LOG"
    fi
    sleep 0.2
done

log ""
log "── Check: do they share ONE actions bucket? ──"
log "If all /actions endpoints share a single 7200 bucket, the Remaining"
log "values above should form a single decreasing sequence."
log ""

# After hitting action endpoints, check general bucket again
log "── General bucket after action scanning ──"
scan "/ssh_keys"
log ""

log "Done: $(date -u '+%Y-%m-%d %H:%M:%S UTC')"

This commit adds retries with exponential backoff for API calls that hit
the rate-limit.

It also adds a way for the caller to have visibility into the
Rate-Limits, so the 429s do not necessarily come as a surprise.
The RateLimitBuckets object is optional (old code will continue working
as before) and can be provided only when visibility into the budget left
in the rate-limit quota is desired.
@sonarqubecloud

Copy link
Copy Markdown

@rkosegi
rkosegi merged commit 9ea6472 into dNationCloud:main Nov 23, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants