TsgcWSRateLimiter › Methods › Consume
Consumes cost tokens and returns a detailed TsgcRateLimitResult.
function Consume(const aKey: string; aCost: Integer = 1) : TsgcRateLimitResult;
| Name | Type | Description |
|---|---|---|
aKey | const string | Rate-limit key to evaluate (IP, apikey:XXX, user:... or an endpoint path). Used by ResolveRule to pick PerEndpoint / PerAPIKey / PerUser / PerIP, and otherwise falls back to the global strategy. |
aCost | Integer | Number of tokens (or slots) to consume from the budget. Defaults to 1. Use a higher value for expensive operations so a single call counts as several requests. |
A TsgcRateLimitResult record with Allowed (Boolean), Remaining (tokens/slots left), RetryAfterSec (seconds the caller should wait) and Reason ("token_bucket", "sliding_window", "fixed_window", "burst", "quota:Name" or "" when allowed). (TsgcRateLimitResult)
The core allowance-check primitive. Evaluates, in order, burst protection, the scoped rule (PerEndpoint -> PerAPIKey -> PerUser -> PerIP) or global strategy (TokenBucket -> SlidingWindow -> FixedWindow), then quotas. Updates internal counters, increments Stats, and fires OnThrottled (with an Allow var parameter that lets the handler overturn a rejection) or OnQuotaExceeded. Use the returned RetryAfterSec to populate the HTTP Retry-After header.
var
oResult: TsgcRateLimitResult;
begin
oResult := sgcWSRateLimiter1.Consume('apikey:' + ApiKey);
if not oResult.Allowed then
begin
Response.StatusCode := 429;
Response.CustomHeaders.Values['Retry-After'] := IntToStr(oResult.RetryAfterSec);
Response.ContentText := 'Throttled: ' + oResult.Reason;
Exit;
end;
end;