TsgcWSRateLimiterMethods › Consume

Consume Method

Consumes cost tokens and returns a detailed TsgcRateLimitResult.

Syntax

function Consume(const aKey: string; aCost: Integer = 1) : TsgcRateLimitResult;

Parameters

NameTypeDescription
aKeyconst stringRate-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.
aCostIntegerNumber 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.

Return Value

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)

Remarks

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.

Example

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;

Back to Methods