PeaLang Code Library

API Reliability & Security

Rate limiters, quotas, signing, retries, idempotency, keys, tenants and authorisation checks.

1. Token bucket rate limiter for a public API

Use case. A payments API must reject a burst after 60 requests per minute without treating intentionally expensive endpoints the same as reads. Put bucket creation, refill and consumption in one deterministic rule so gateways never disagree on allow/reject.

# Inputs: current token state, now in seconds, request class.
const CAPACITY = 60
const REFILL_PER_SEC = 1.0
const COST = 1

function consume(state, now) {
    # Refill before deciding; tolerance handles small negative deltas.
    let elapsed = now - state.updated_at
    if elapsed < 0 { elapsed = 0 }
    let refill = elapsed * REFILL_PER_SEC
    let tokens = state.tokens + refill
    if tokens > CAPACITY { tokens = CAPACITY }
    if tokens < COST {
        return {"allowed": false, "remaining": tokens, "retry_after_s": 1}
    }
    return {"allowed": true, "remaining": tokens - COST, "retry_after_s": 0}
}

let state = {"tokens": 3.0, "updated_at": 1000}
let now = 1002
let result = consume(state, now)
print "RATE={result.allowed} REMAINING={result.remaining}"

Save as api-reliability-security_01.pea; check pea fmt --check api-reliability-security_01.pea && pea check api-reliability-security_01.pea; run pea run api-reliability-security_01.pea.

2. Idempotency key replay protection

Use case. A webhook receiver must process the same logical event once even if the sender retries after timeout. Store a stable key and prior outcome so a replayed key returns the first answer instead of re-executing the side effect.

# Host passes stored_response or null when key is unseen.
function replay_result(key, stored) {
    if key == "" {
        return {"status": "INVALID", "code": "MISSING_KEY"}
    }
    if stored == null {
        return {"status": "EXECUTE", "code": "NEW"}
    }
    return {"status": "REPLAY", "code": "IDEMPOTENT_HIT", "result": stored}
}

let decision = replay_result("evt_2026_11_17_0001", {"status_code": 201, "resource": "ord_1042"})
print "ACTION={decision.status}"

Save as api-reliability-security_02.pea; check pea fmt --check api-reliability-security_02.pea && pea check api-reliability-security_02.pea; run pea run api-reliability-security_02.pea.

3. API key scope verifier

Use case. Partner keys arrive with coarse scopes such as read:all and write:orders. Before the handler mutates a resource, verify the exact action and object class and fail closed on missing or mismatched scopes.

# Exact-match scopes beat wildcard prefix logic when contracts matter.
const REQUIRED_SCOPE = "orders:write"

function has_scope(scopes, need) {
    let i = 0
    while i < len(scopes) {
        if scopes[i] == need { return true }
        i += 1
    }
    return false
}

let scopes = ["orders:read", "orders:write", "inventory:read"]
print "ALLOWED={has_scope(scopes, REQUIRED_SCOPE)}"

Save as api-reliability-security_03.pea; check pea fmt --check api-reliability-security_03.pea && pea check api-reliability-security_03.pea; run pea run api-reliability-security_03.pea.

4. Request HMAC freshness window

Use case. A signed API call must not be replayed hours later. The gateway has the received signature and timestamp but should not trust either until it recomputes HMAC and enforces a maximum clock skew.

# Timestamp is already parsed by the host; this rule owns the policy.
const MAX_SKEW_SECONDS = 300

function verify_time(timestamp, now) {
    let drift = now - timestamp
    if drift < 0 { drift = 0 - drift }
    if drift > MAX_SKEW_SECONDS {
        return {"ok": false, "reason": "SKEW"}
    }
    return {"ok": true, "reason": "FRESH"}
}

print "AUTH={verify_time(1710000200, 1710000450).ok}"

Save as api-reliability-security_04.pea; check pea fmt --check api-reliability-security_04.pea && pea check api-reliability-security_04.pea; run pea run api-reliability-security_04.pea.

5. Daily tenant quota rejector

Use case. Free-tier tenants can call public endpoints but cannot exceed a contracted daily budget. The decision must be atomic enough that concurrent workers rely on the same counters and same deny answer.

# Host supplies current day counter and tier limit.
const LIMITS = {"free": 10000, "pro": 500000, "enterprise": 5000000}

function check_quota(tier, used, requested) {
    if not (tier in LIMITS) {
        return {"ok": false, "reason": "UNKNOWN_TIER"}
    }
    let limit = LIMITS[tier]
    if used + requested > limit {
        return {"ok": false, "reason": "QUOTA_EXCEEDED", "limit": limit}
    }
    return {"ok": true, "reason": "OK", "remaining": limit - used - requested}
}

print "QUOTA={check_quota("free", 9950, 60).ok}"

Save as api-reliability-security_05.pea; check pea fmt --check api-reliability-security_05.pea && pea check api-reliability-security_05.pea; run pea run api-reliability-security_05.pea.

6. JWT issuer and audience policy

Use case. A service mesh passes decoded claims from every issuer. The application must reject tokens meant for another service even if they are cryptographically valid, because valid signature is necessary but not sufficient.

# Claims arrived as a portable map from the identity gateway.
const EXPECTED_ISS = "https://idp.example.com"
const EXPECTED_AUD = "orders-api"

function claims_ok(claims) {
    if claims.iss != EXPECTED_ISS { return {"ok": false, "reason": "ISS"} }
    if "orders-api" in claims.aud {
        return {"ok": true, "reason": "OK"}
    }
    return {"ok": false, "reason": "AUD"}
}

print "JWT={claims_ok({"iss":"https://idp.example.com","aud":["billing-api","orders-api"]}).reason}"

Save as api-reliability-security_06.pea; check pea fmt --check api-reliability-security_06.pea && pea check api-reliability-security_06.pea; run pea run api-reliability-security_06.pea.

7. Safe retry classification for API clients

Use case. Retry middleware cannot retry auth failures or validation errors, no matter how cheap the call is. It may only retry transient failures or explicitly idempotent 5xx/timeout responses from known hosts.

# Status and body class are already redacted by the host.
function retryable(status, body_class, idempotent) {
    if status == 429 and idempotent { return true }
    if status >= 500 and idempotent { return true }
    if status == 0 and idempotent { return true }
    return false
}

print "RETRY={retryable(503, "upstream", true)}"

Save as api-reliability-security_07.pea; check pea fmt --check api-reliability-security_07.pea && pea check api-reliability-security_07.pea; run pea run api-reliability-security_07.pea.

8. Field-level redaction for support logs

Use case. Support exports customer logs into tickets; email addresses, cards and secrets must never pass through unfiltered. The redaction rule is code, not a wiki page, so it can be reviewed and regression-tested.

# Simple deterministic scrub before log write.
const REPLACEMENT = "[REDACTED]"
let message = "user ava@example.com card 4111-1111-1111-1111"
if "@" in message {
    message = "user [REDACTED] card 4111-1111-1111-1111"
}
if "4111-1111-1111-1111" in message {
    message = "user [REDACTED] card [REDACTED]"
}
print "LOG={message}"

Save as api-reliability-security_08.pea; check pea fmt --check api-reliability-security_08.pea && pea check api-reliability-security_08.pea; run pea run api-reliability-security_08.pea.

9. Circuit breaker for a flaky dependency

Use case. When a pricing provider starts timing out, repeated calls amplify failure and waste budget. The breaker must move clients to cached/default behavior once failure share crosses the configured threshold.

# Window metrics are aggregated by the host every 30s.
const OPEN_RATIO = 0.5
const MIN_SAMPLES = 20

function breaker(samples, failures) {
    if samples < MIN_SAMPLES {
        return {"state": "CLOSED", "reason": "INSUFFICIENT_EVIDENCE"}
    }
    let ratio = failures / samples
    if ratio >= OPEN_RATIO {
        return {"state": "OPEN", "reason": "HIGH_FAILURE_SHARE", "ratio": ratio}
    }
    return {"state": "CLOSED", "reason": "HEALTHY", "ratio": ratio}
}

print "BREAKER={breaker(100, 61).state}"

Save as api-reliability-security_09.pea; check pea fmt --check api-reliability-security_09.pea && pea check api-reliability-security_09.pea; run pea run api-reliability-security_09.pea.

10. Seat license enforcement for admin invitations

Use case. An admin console can apply invitations even when the contract has no seats left. Enforce contract occupancy on the server, not just in the UI, and refuse before billing is charged.

# The host supplies contracted seats and active seats from billing.
const SEAT_LIMIT = 25

function invite_allowed(active, invited) {
    let projected = active + invited
    if projected > SEAT_LIMIT {
        return {"ok": false, "reason": "SEAT_LIMIT", "remaining": SEAT_LIMIT - active}
    }
    return {"ok": true, "reason": "OK", "remaining": SEAT_LIMIT - projected}
}

print "INVITE={invite_allowed(24, 2).ok}"

Save as api-reliability-security_10.pea; check pea fmt --check api-reliability-security_10.pea && pea check api-reliability-security_10.pea; run pea run api-reliability-security_10.pea.

← Back to the Code Library