Token Bucket Algorithm In C#

The token bucket is an algorithm used in packet switched computer networks and telecommunications networks to check that data transmissions conform to defined limits on bandwidth and burstiness (a measure of the unevenness or variations in the traffic flow).…more

using System;
using System.DateTime;

public class TokenBucket
	float _capacity = 0;
	float _tokens   = 0;
	float _fillrate = 0;
    DateTime _time_stamp;

	public TokenBucket(float tokens, float fill_rate)
		_capacity  = tokens;
		_tokens    = tokens;
		_fill_rate = fill_rate;
		_time_stamp = DateTime.Now;

	public bool Consume(float tokens)
		if(tokens 		{
			_tokens -= tokens;
			return false;
		return true;

	public float GetTokens()
		DateTime _now = DateTime.Now;
		if(_tokens < _capacity)
			var delta = _fill_rate * (_now - _time_stamp);
			_tokens = Math.Min(_capacity, _tokens + delta);
			_time_stamp = _now;
		return _tokens;

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s