RingDotNetfor Ring

Rate limiting

A service that answers every request can be brought down by one client that asks too often. A rate limiter says yes or no to each request at once. This lesson uses a token bucket, a concurrency limiter with leases, statistics and the retry time, and keeps one limiter for each client.

What you will learn#

A web program (the tutorial A web service with a database) uses limiters to answer 429 Too Many Requests, a client that calls an API (the tutorial HttpClient in depth) uses one to stay below the limit of the server, and a program that sends mail uses one so that it is not marked as spam.

Note

System.Threading.RateLimiting is part of the ASP.NET Core runtime, so the program has "RingDotNet.Web" in its using { } (Getting started). The namespace has no generated Ring classes: the objects are made with dnNew(type, [options]) and used with callMethod and getProp (Core concepts).

The program#

samples/UsingDotNet/tutorials/ch08_rate_limiting.ring
# rate limiting - a token bucket, a concurrency limiter with leases, statistics, and one limiter for each client
load "dotnet.ring"

using {
	"System.Threading.RateLimiting"
	"System"
	"System.Threading"
	"RingDotNet.Web"                  # System.Threading.RateLimiting is part of the ASP.NET Core runtime: this line starts it
}


func main

	# A rate limiter protects a service from too many requests: a client that asks 1000 times a second, a script with a bug, an attack.
	# It says YES or NO to each request at once (AttemptAcquire), without waiting. The program decides what NO means (an error 429
	# "Too Many Requests", a pause, a message).

	# 1. TOKEN BUCKET: a bucket that holds up to 3 tokens. Each request takes one. Tokens come back one at a time at a fixed pace.
	#    A client can make a short burst (3 requests at once) but not more than the pace in the long run.
	#    AutoReplenishment is off here: the program adds the tokens itself with TryReplenish, which adds one only when the period (here
	#    100 ms) has passed since the last time. (With AutoReplenishment on, a timer of the limiter does it.)
	oBucket = makeBucket(3,100)
	? "1. a bucket of 3 tokens, 5 requests at once:"
	for nRequest = 1 to 5
		oLease = oBucket.AttemptAcquire(1)
		? "   request " + nRequest + ": " + answer(oLease.IsAcquired)
	next
	new Thread().Sleep(300)      # more than the period of 100 ms
	? "   after the period, TryReplenish adds a token: " + oBucket.TryReplenish()
	? "   the next request: " + answer(oBucket.AttemptAcquire(1).IsAcquired) + "   (how many tokens come back depends on how long the pause was)"

	# 2. Statistics: how many tokens are left, how many requests were granted and how many refused
	oStatistics = oBucket.GetStatistics()
	? nl + "2. tokens left (not more than the bucket holds): " + (oStatistics.CurrentAvailablePermits <= 3) + ", granted in total: " + oStatistics.TotalSuccessfulLeases + ", refused in total: " + oStatistics.TotalFailedLeases

	# 3. CONCURRENCY LIMITER: at most 2 requests are being handled at the same time. A request gets a LEASE and gives it back when it is
	#    finished (Dispose). While two leases are out, the third request is refused. This protects a slow resource (a database connection).
	oConcurrency = new ConcurrencyLimiter(makeConcurrencyOptions(2))
	oLeaseA = oConcurrency.AttemptAcquire(1)
	oLeaseB = oConcurrency.AttemptAcquire(1)
	oLeaseC = oConcurrency.AttemptAcquire(1)
	? nl + "3. three requests at once, 2 allowed: " + answer(oLeaseA.IsAcquired) + ", " + answer(oLeaseB.IsAcquired) + ", " + answer(oLeaseC.IsAcquired)
	oLeaseA.Dispose()                  # the first request is finished: its place is free
	oLeaseD = oConcurrency.AttemptAcquire(1)
	? "   after the first one finished, a new request: " + answer(oLeaseD.IsAcquired)

	# 4. Why a request was refused: a refused lease can carry the time to wait (the metadata RETRY_AFTER). The answer to the client
	#    ("try again in 5 seconds") is better than only "no".
	oSlow = makeBucket(1,5000)
	oSlow.AttemptAcquire(1)
	oRefused = oSlow.AttemptAcquire(1)
	aRetry = oRefused.TryGetMetadata("RETRY_AFTER")
	? nl + "4. the bucket is empty: refused, a retry time is offered: " + aRetry[1]
	if aRetry[1]
		? "   try again after about " + floor(aRetry[2].TotalSeconds + 0.5) + " seconds"
	ok

	# 5. One limiter for each client: a Ring list keeps a bucket for every client name (an IP address, a user id), so that one noisy
	#    client does not use up the allowance of the others.
	aClients = []
	for cClient in ["10.0.0.1","10.0.0.2"]
		aClients + [cClient,makeBucket(2,5000)]
	next
	? nl + "5. two clients with 2 requests each; the first client asks 4 times, the second twice:"
	? "   10.0.0.1: " + asks(aClients[1][2],4)
	? "   10.0.0.2: " + asks(aClients[2][2],2)

func makeBucket nTokens,nPeriodMs

	oOptions = new TokenBucketRateLimiterOptions
	oOptions.TokenLimit = nTokens
	oOptions.TokensPerPeriod = 1
	oPeriod = new TimeSpan().FromMilliseconds(nPeriodMs)
	oOptions.ReplenishmentPeriod = oPeriod
	oOptions.AutoReplenishment = False
	oOptions.QueueLimit = 0
	return new TokenBucketRateLimiter(oOptions)

func makeConcurrencyOptions nLimit

	oOptions = new ConcurrencyLimiterOptions
	oOptions.PermitLimit = nLimit
	oOptions.QueueLimit = 0
	return oOptions

# the answers of one client for n requests, as a text of yes and no
func asks oBucket,nCount

	cText = ""
	for i = 1 to nCount
		cText += answer(oBucket.AttemptAcquire(1).IsAcquired) + " "
	next
	return cText

func answer lYes

	if lYes
		return "allowed"
	ok
	return "refused"
Output
1. a bucket of 3 tokens, 5 requests at once:
   request 1: allowed
   request 2: allowed
   request 3: allowed
   request 4: refused
   request 5: refused
   after the period, TryReplenish adds a token: 1
   the next request: allowed   (how many tokens come back depends on how long the pause was)

2. tokens left (not more than the bucket holds): 1, granted in total: 4, refused in total: 2

3. three requests at once, 2 allowed: allowed, allowed, refused
   after the first one finished, a new request: allowed

4. the bucket is empty: refused, a retry time is offered: 1
   try again after about 5 seconds

5. two clients with 2 requests each; the first client asks 4 times, the second twice:
   10.0.0.1: allowed allowed refused refused 
   10.0.0.2: allowed allowed
Note

This program uses a few generic functions (dnNew, callMethod, getProp, setProp) where a class cannot be used. The lesson The generic functions explains them.

How it works#

Yes or no at once#

AttemptAcquire(1) asks for one permit and answers immediately with a lease; IsAcquired says whether the permit was given. The limiter never waits in this call: what a no means is the program's decision (an error to the client, a pause, a message). (AcquireAsync can wait in a queue; with QueueLimit = 0, as here, nothing waits.)

The token bucket#

The bucket holds up to TokenLimit tokens (3). Each request takes one. Tokens come back at a fixed pace: TokensPerPeriod tokens every ReplenishmentPeriod. So a client can make a burst — here 3 requests at once — and then only as many as the pace allows. This is the usual shape of real traffic, which is why the token bucket is the most common limiter. With AutoReplenishment on, a timer of the limiter adds the tokens; the program turns it off and calls TryReplenish() itself, so that the example does not depend on a timer. TryReplenish adds tokens only when the period has passed since the last time, which is why the program waits a little first. How many tokens come back depends on how long the pause was; the output states only what is always true.

Statistics#

GetStatistics() gives CurrentAvailablePermits (how many are left), TotalSuccessfulLeases and TotalFailedLeases. The totals show how much traffic was turned away: 4 granted and 2 refused here (the first three requests and the one after the pause were granted; requests 4 and 5 were refused). Show them on a status page and in the log.

The concurrency limiter#

It limits not the rate but how many requests are in progress at the same time: with a limit of 2, the third request is refused until one of the first two ends. A request keeps its lease while it works and gives it back with Dispose(); then the place is free again, and the next request is allowed. Use it for a slow shared resource: a database with 10 connections, a report that uses a lot of memory. Always dispose the lease in every path, including errors (try / catch, the tutorial When things go wrong), or the places are lost one by one.

The retry time#

A refused lease can say when to try again: TryGetMetadata("RETRY_AFTER") answers [ found, TimeSpan ] (the tutorial Network tools). A web server puts the seconds in the Retry-After header of the 429 response, and a well-made client waits that long and does not hammer the server.

One limiter for each client#

A single bucket for the whole service lets one noisy client use up the allowance of everybody. The program keeps a bucket for each client in a Ring list (the key is an address or a user id): the first client is refused after 2 requests while the second still has its allowance. In a real service the list is a dictionary, and old clients are removed so that it does not grow for ever (the tutorial Caching shows a cache with expiration for this).

Warning

The limiter lives inside the program: two copies of a service have two separate buckets, so a client can make twice as many requests. For a limit that holds across servers, count in a shared store (a database or a cache server). And the address of a client behind a proxy is the address of the proxy (the tutorial IP networks).

What you learned#

Exercises#

  1. Write handleRequest(cClient) that returns 200 or 429 and the retry seconds, using one bucket for each client name.
  2. Use a FixedWindowRateLimiter (a window of 1 second, 5 permits) and make 10 requests with short pauses.
  3. Combine a concurrency limiter with a token bucket: a request must pass both.
  4. Print the statistics of every client after 100 random requests (the tutorial Randomness).

Where to go next#

This was the last tutorial of the chapter Security. The next chapter is Databases and services: it starts with Databases step by step. The Tutorials page lists all the chapters, and you can start any of them.

RingDotNet — use .NET classes and methods from Ring programs. Screenshots and output on these pages come from the real samples.