Rate Limiter
Per-connection and per-key rate-limiting component — token bucket and fixed-window strategies for any sgcWebSockets server.
Per-connection and per-key rate-limiting component — token bucket and fixed-window strategies for any sgcWebSockets server.
TsgcWSRateLimiter implements a full-featured rate limiting component that protects server endpoints from excessive traffic, abuse and scraping.
TsgcWSRateLimiter| Component class | TsgcWSRateLimiter (unit sgcWebSocket_RateLimiter) |
| Frameworks | VCL, FireMonkey, Lazarus / FPC |
| Platforms | Windows, macOS, Linux, iOS, Android |
The principal published / public properties used to configure and drive the component. Consult the online help for the full list.
PerAPIKey | Rate-limit rule scoped to an API-key identifier (keys prefixed apikey:). |
TokenBucket | Token Bucket algorithm configuration: capacity plus refill rate for smooth bursts. |
PerEndpoint | Collection of pattern-based rules matched by wildcard against the request key. |
Enabled | Master switch that turns the entire rate limiter on or off. |
SlidingWindow | Sliding Window algorithm configuration: MaxRequests over a rolling WindowSec. |
FixedWindow | Fixed Window algorithm configuration: MaxRequests inside a clock-aligned WindowSec. |
BurstProtection | Short-timescale spike detector that puts abusive keys into a cooldown. |
PerIP | Rate-limit rule scoped to the source IP address. |
PerUser | Rate-limit rule scoped to a user identifier (keys prefixed user:). |
Quotas | Long-term caps (hour/day/month) evaluated on top of the main strategy. |
The principal public methods exposed by the component.
IsConnectionAllowed() | Server hook: returns True if a new connection from IP passes rate limiting. |
RegisterConnection() | Registers a new connection for tracking (called automatically by the server). |
UnregisterConnection() | Removes a connection from tracking (called automatically on disconnect). |
Reset() | Clears the counters for a single key. |
ResetAll() | Clears every internal counter and resets the Stats object. |
SaveStateToStream() | Persists the internal state to an arbitrary TStream. |
LoadStateFromStream() | Restores the internal state from an arbitrary TStream. |
IsAllowed() | Returns True if a request of the given cost is allowed for the specified key. |
Consume() | Consumes cost tokens and returns a detailed TsgcRateLimitResult. |
IsMessageAllowed() | Server hook: returns True if a message from IP passes rate limiting. |
The component exposes the following published events; consult the online help for full event-handler signatures.
OnQuotaExceeded | property OnQuotaExceeded: TsgcRateLimitOnQuotaExceeded; // TsgcRateLimitOnQuotaExceeded = procedure(Sender: TObject; const aKey, aQuotaName: string) of object __property TsgcRateLimitOnQuotaExceeded O... |
OnStateChange | property OnStateChange: TsgcRateLimitOnStateChange; // TsgcRateLimitOnStateChange = procedure(Sender: TObject; const aKey: string; aOldBucketSize, aNewBucketSize: Integer) of object __property TsgcRat... |
OnThrottled | Fired when a request is rejected by the strategy or burst protection. |
Drop the component on a form, configure the properties below and activate it. The snippet that follows shows the typical IsConnectionAllowed configuration sourced from the online help.
// Manual gate in a custom OnConnect handler procedure TForm1.ServerConnect(Connection: TsgcWSConnection); begin if not sgcWSRateLimiter1.IsConnectionAllowed(Connection.PeerIP) then Connection.Disconnect; end;
The following scenarios are lifted verbatim from the online help. Each shows the configuration and method calls needed to drive the component through a specific real-world flow.
Registers a new connection for tracking (called automatically by the server).
procedure TForm1.ServerConnect(Connection: TsgcWSConnection); begin sgcWSRateLimiter1.RegisterConnection(Connection.PeerIP); end;
Removes a connection from tracking (called automatically on disconnect).
procedure TForm1.ServerDisconnect(Connection: TsgcWSConnection); begin sgcWSRateLimiter1.UnregisterConnection(Connection.PeerIP); end;
Short-timescale spike detector that puts abusive keys into a cooldown.
// More than 50 requests in 500ms triggers a 30-second cooldown sgcWSRateLimiter1.BurstProtection.Enabled := True; sgcWSRateLimiter1.BurstProtection.BurstThreshold := 50; sgcWSRateLimiter1.BurstProtection.BurstWindowMs := 500; sgcWSRateLimiter1.BurstProtection.CooldownSec := 30;
Consumes cost tokens and returns a detailed TsgcRateLimitResult.
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;
Master switch that turns the entire rate limiter on or off.
// Temporarily disable rate limiting during a load test sgcWSRateLimiter1.Enabled := False; try RunLoadTest; finally sgcWSRateLimiter1.Enabled := True; end;
Fixed Window algorithm configuration: MaxRequests inside a clock-aligned WindowSec.
// Billing-style: 1000 requests per hour, resets on the hour sgcWSRateLimiter1.FixedWindow.Enabled := True; sgcWSRateLimiter1.FixedWindow.WindowSec := 3600; sgcWSRateLimiter1.FixedWindow.MaxRequests := 1000;
Every external claim links back to a primary source. The online-help references decode the canonical deep-link the company maintains for this component.
Demos\04.WebSocket_Other_Samples\14.RateLimiter