Overview

Rate Limiting

Showcases high-concurrency state management and request throttling using thread-safe global storage. This example demonstrates the 'IncrementGlobalVar' atomic operation, illustrating how to implement sophisticated IP-based rate limiting with automatic temporal expiration (TTL), essential for protecting public API endpoints from denial-of-service and brute-force attacks in a distributed web environment.

Source Code

var remoteIP := WebRequest.RemoteIP;
if remoteIP = '' then remoteIP := '127.0.0.1'; // Fallback for testing

// Define the rate limit key
var rateKey := 'RateLimit.Demo.' + remoteIP;

// Increment the counter. The expiration (10.0 seconds) means that
// if the user stops making requests for 10 seconds, the counter is deleted.
var requestCount := IncrementGlobalVar(rateKey, 1, 10.0);

PrintLn('<h3>Rate Limiter Demo</h3>');
PrintLn('<p>IP Address: ' + remoteIP + '</p>');
PrintLn('<p>Request count in the last 10 seconds: <strong>' + IntToStr(requestCount) + '</strong></p>');

if requestCount > 5 then begin
   PrintLn('<div class="alert alert-danger">');
   PrintLn('  <strong>Limit Exceeded!</strong> You have made more than 5 requests in 10 seconds.');
   PrintLn('  Please wait 10 seconds before trying again.');
   PrintLn('</div>');
end else begin
   PrintLn('<div class="alert alert-success">');
   PrintLn('  <strong>Access Granted.</strong> You are within the allowed limit (5 requests per 10s).');
   PrintLn('  Refresh this page rapidly to trigger the rate limit.');
   PrintLn('</div>');
end;

PrintLn('<hr>');
PrintLn('<p><small>The rate limit is tracked using a thread-safe global variable that expires automatically.</small></p>');

Result

<h3>Rate Limiter Demo</h3>
<p>IP Address: ::1</p>
<p>Request count in the last 10 seconds: <strong>1</strong></p>
<div class="alert alert-success">
  <strong>Access Granted.</strong> You are within the allowed limit (5 requests per 10s).
  Refresh this page rapidly to trigger the rate limit.
</div>
<hr>
<p><small>The rate limit is tracked using a thread-safe global variable that expires automatically.</small></p>
On this page