The Wayback Machine - https://web.archive.org/web/20240815223009/https://www.geeksforgeeks.org/leaky-bucket-algorithm/
Open In App

Computer Network | Leaky bucket algorithm

Last Updated : 05 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In the network layer, before the network can make Quality of service guarantees, it must know what traffic is being guaranteed. One of the main causes of congestion is that traffic is often bursty. 

To understand this concept first we have to know little about traffic shaping. Traffic Shaping is a mechanism to control the amount and the rate of traffic sent to the network. Approach of congestion management is called Traffic shaping. Traffic shaping helps to regulate the rate of data transmission and reduces congestion.

There are 2 types of traffic shaping algorithms: 

  1. Leaky Bucket
  2. Token Bucket

Suppose we have a bucket in which we are pouring water, at random points in time, but we have to get water at a fixed rate, to achieve this we will make a hole at the bottom of the bucket. This will ensure that the water coming out is at some fixed rate, and also if the bucket gets full, then we will stop pouring water into it.

The input rate can vary, but the output rate remains constant. Similarly, in networking, a technique called leaky bucket can smooth out bursty traffic. Bursty chunks are stored in the bucket and sent out at an average rate.

In the above figure, we assume that the network has committed a bandwidth of 3 Mbps for a host. The use of the leaky bucket shapes the input traffic to make it conform to this commitment. In the above figure, the host sends a burst of data at a rate of 12 Mbps for 2s, for a total of 24 Mbits of data. The host is silent for 5 s and then sends data at a rate of 2 Mbps for 3 s, for a total of 6 Mbits of data. In all, the host has sent 30 Mbits of data in 10 s. The leaky bucket smooths out the traffic by sending out data at a rate of 3 Mbps during the same 10 s. 

Without the leaky bucket, the beginning burst may have hurt the network by consuming more bandwidth than is set aside for this host. We can also see that the leaky bucket may prevent congestion.

A simple leaky bucket algorithm can be implemented using FIFO queue. A FIFO queue holds the packets. If the traffic consists of fixed-size packets (e.g., cells in ATM networks), the process removes a fixed number of packets from the queue at each tick of the clock. If the traffic consists of variable-length packets, the fixed output rate must be based on the number of bytes or bits.

The following is an algorithm for variable-length packets:  

  1. Initialize a counter to n at the tick of the clock.
  2. Repeat until n is smaller than the packet size of the packet at the head of the queue.
    1. Pop a packet out of the head of the queue, say P.
    2. Send the packet P, into the network 
    3. Decrement the counter by the size of packet P.
  3. Reset the counter and go to step 1.

Note: In the below examples, the head of the queue is the rightmost position and the tail of the queue is the leftmost position.

Example: Let n=1000 

Packet=

leaky_algorithm_2

 
Since n > size of the packet at the head of the Queue, i.e. n > 200 
Therefore, n = 1000-200 = 800 
Packet size of 200 is sent into the network. 
 

leaky_algorithm_2

Now, again n > size of the packet at the head of the Queue, i.e. n > 400 
Therefore, n = 800-400 = 400 
Packet size of 400 is sent into the network. 
 

leaky_algorithm_2

Since, n < size of the packet at the head of the Queue, i.e.  n < 450
Therefore, the procedure is stopped.

Initialise n = 1000 on another tick of the clock. 
This procedure is repeated until all the packets are sent into the network.

Below is the implementation of above explained approach: 
 

C++




// cpp program to implement leakybucket
#include <bits/stdc++.h>
using namespace std;
int main()
{
    int no_of_queries, storage, output_pkt_size;
    int input_pkt_size, bucket_size, size_left;
 
    // initial packets in the bucket
    storage = 0;
 
    // total no. of times bucket content is checked
    no_of_queries = 4;
 
    // total no. of packets that can
    // be accommodated in the bucket
    bucket_size = 10;
 
    // no. of packets that enters the bucket at a time
    input_pkt_size = 4;
 
    // no. of packets that exits the bucket at a time
    output_pkt_size = 1;
    for (int i = 0; i < no_of_queries; i++) // space left
    {
        size_left = bucket_size - storage;
        if (input_pkt_size <= size_left) {
            // update storage
            storage += input_pkt_size;
        }
        else {
            printf("Packet loss = %d\n", input_pkt_size);
        }
        printf("Buffer size= %d out of bucket size= %d\n",
               storage, bucket_size);
        storage -= output_pkt_size;
    }
    return 0;
}
 
// This code is contributed by bunny09262002
// Improved by: rishitchaudhary


Java




// Java Implementation of Leaky bucket
 
import java.io.*;
import java.util.*;
 
class Leakybucket {
    public static void main(String[] args)
    {
        int no_of_queries, storage, output_pkt_size;
        int input_pkt_size, bucket_size, size_left;
 
        // initial packets in the bucket
        storage = 0;
 
        // total no. of times bucket content is checked
        no_of_queries = 4;
 
        // total no. of packets that can
        // be accommodated in the bucket
        bucket_size = 10;
 
        // no. of packets that enters the bucket at a time
        input_pkt_size = 4;
 
        // no. of packets that exits the bucket at a time
        output_pkt_size = 1;
        for (int i = 0; i < no_of_queries; i++) {
            size_left = bucket_size - storage; // space left
 
            if (input_pkt_size <= (size_left)) {
                storage += input_pkt_size;
            }
            else {
                System.out.println("Packet loss = "
                                   + input_pkt_size);
            }
            System.out.println("Buffer size= " + storage
                               + " out of bucket size= "
                               + bucket_size);
            storage -= output_pkt_size;
        }
    }
}
// Improved by: rishitchaudhary


Python3




# initial packets in the bucket
storage = 0
 
# total no. of times bucket content is checked
no_of_queries = 4
 
# total no. of packets that can
# be accommodated in the bucket
bucket_size = 10
 
# no. of packets that enters the bucket at a time
input_pkt_size = 4
 
# no. of packets that exits the bucket at a time
output_pkt_size = 1
for i in range(0, no_of_queries):  # space left
 
    size_left = bucket_size - storage
    if input_pkt_size <= size_left:
      # update storage
        storage += input_pkt_size
    else:
        print("Packet loss = ", input_pkt_size)
 
    print(f"Buffer size= {storage} out of bucket size = {bucket_size}")
 
    # as packets are sent out into the network, the size of the storage decreases
    storage -= output_pkt_size
 
 
# This code is contributed by Arpit Jain
# Improved by: rishitchaudhary


C#




// C# Implementation of Leaking bucket
using System;
 
class Leakingbucket
{
  static void Main(string[] args)
  {
    int no_of_queries, storage, output_pkt_size;
    int input_pkt_size, bucket_size, size_left;
 
    // initial packets in the bucket
    storage = 0;
 
    // total no. of times bucket content is checked
    no_of_queries = 4;
 
    // total no. of packets that can
    // be accommodated in the bucket
    bucket_size = 10;
 
    // no. of packets that enters the bucket at a time
    input_pkt_size = 4;
 
    // no. of packets that exits the bucket at a time
    output_pkt_size = 1;
    for (int i = 0; i < no_of_queries; i++)
    {
      size_left = bucket_size - storage; // space left
 
      if (input_pkt_size <= (size_left))
      {
        storage += input_pkt_size;
      }
      else
      {
        Console.WriteLine("Packet loss = " + input_pkt_size);
      }
      Console.WriteLine("Buffer size= " + storage + " out of bucket size= " + bucket_size);
      storage -= output_pkt_size;
    }
  }
}
 
// This code is Contributed by phasing17


Javascript




// JS code to implement the approach
 
// initial packets in the bucket
let storage = 0;
 
// total no. of times bucket content is checked
let noOfQueries = 4;
 
// total no. of packets that can
// be accommodated in the bucket
let bucketSize = 10;
 
// no. of packets that enters the bucket at a time
let inputPktSize = 4;
 
// no. of packets that exits the bucket at a time
let outputPktSize = 1;
 
for (let i = 0; i < noOfQueries; i++) { // space left
 
let sizeLeft = bucketSize - storage;
if (inputPktSize <= sizeLeft) {
// update storage
storage += inputPktSize;
} else {
console.log("Packet loss = ", inputPktSize);
}
 
console.log(`Buffer size= ${storage} out of bucket size = ${bucketSize}`);
 
// as packets are sent out into the network, the size of the storage decreases
storage -= outputPktSize;
}
 
// This code is contributed by phasing17


Output 
 

Buffer size= 4 out of bucket size= 10
Buffer size= 7 out of bucket size= 10
Buffer size= 10 out of bucket size= 10
Packet loss = 4
Buffer size= 9 out of bucket size= 10

Difference between Leaky and Token buckets –
 

Leaky Bucket Token Bucket
When the host has to send a packet , packet is thrown in bucket. In this, the bucket holds tokens generated at regular intervals of time.
Bucket leaks at constant rate Bucket has maximum capacity.
Bursty traffic is converted into uniform traffic by leaky bucket. If there is a ready packet , a token is removed from Bucket and packet is send.
In practice bucket is a finite queue outputs at finite rate If there is no token in the bucket, then the packet cannot be sent.

Some advantage of token Bucket over leaky bucket

  • If a bucket is full in tokens Bucket, tokens are discard not packets. While in leaky bucket, packets are discarded.
  • Token Bucket can send large bursts at a faster rate while leaky bucket always sends packets at constant rate.
  • Predictable Traffic Shaping: Token Bucket offers more predictable traffic shaping compared to leaky bucket. With token bucket, the network administrator can set the rate at which tokens are added to the bucket, and the maximum number of tokens that the bucket can hold. This allows for better control over the network traffic and can help prevent congestion.
  • Better Quality of Service (QoS): Token Bucket provides better QoS compared to leaky bucket. This is because token bucket can prioritize certain types of traffic by assigning different token arrival rates to different classes of packets. This ensures that important packets are sent first, while less important packets are sent later, helping to ensure that the network runs smoothly.
  • More efficient use of network bandwidth: Token Bucket allows for more efficient use of network bandwidth as it allows for larger bursts of data to be sent at once. This can be useful for applications that require high-speed data transfer or for streaming video content.
  • More granular control: Token Bucket provides more granular control over network traffic compared to leaky bucket. This is because it allows the network administrator to set the token arrival rate and the maximum token count, which can be adjusted according to the specific needs of the network.
  • Easier to implement: Token Bucket is generally considered easier to implement compared to leaky bucket. This is because token bucket only requires the addition and removal of tokens from a bucket, while leaky bucket requires the use of timers and counters to determine when to release packets.

Some Disadvantage of token Bucket over leaky bucket

  • Tokens may be wasted: In Token Bucket, tokens are generated at a fixed rate, even if there is no traffic on the network. This means that if no packets are sent, tokens will accumulate in the bucket, which could result in wasted resources. In contrast, with leaky bucket, the network only generates packets when there is traffic, which helps to conserve resources.
  • Delay in packet delivery: Token Bucket may introduce delay in packet delivery due to the accumulation of tokens. If the token bucket is empty, packets may need to wait for the arrival of new tokens, which can lead to increased latency and packet loss.
  • Lack of flexibility: Token Bucket is less flexible compared to leaky bucket in terms of shaping network traffic. This is because the token generation rate is fixed, and cannot be changed easily to meet the changing needs of the network. In contrast, leaky bucket can be adjusted more easily to adapt to changes in network traffic.
  • Complexity: Token Bucket can be more complex to implement compared to leaky bucket, especially when different token generation rates are used for different types of traffic. This can make it more difficult for network administrators to configure and manage the network.
  • Inefficient use of bandwidth: In some cases, Token Bucket may lead to inefficient use of bandwidth. This is because Token Bucket allows for large bursts of data to be sent at once, which can cause congestion and lead to packet loss. In contrast, leaky bucket helps to prevent congestion by limiting the amount of data that can be sent at any given time.



Previous Article
Next Article

Similar Reads

Token Bucket Algorithm
The Token Bucket algorithm is a popular and simple method used in computer networking and telecommunications for traffic shaping and rate limiting. It is designed to control the amount of data that a system can send or receive in some sort of period, ensuring that the traffic conforms to a specified rate. It refers to traffic control mechanisms tha
8 min read
Why Star network is More Efficient in Network Fault Tolerance in Place of Bus Network?
Answer: Star networks offer better fault tolerance than bus networks because a single point of failure in a star network (the central hub) affects only the connected device, while a fault in a bus network can disrupt communication for all devices on the bus.Advantages of Star Topology Over Bus Topology Individual Connection Points: In a star networ
2 min read
Basic Network Attacks in Computer Network
Many people rely on the Internet for many of their professional, social and personal activities. But there are also people who attempt to damage our Internet-connected computers, violate our privacy and render inoperable the Internet services. Given the frequency and variety of existing attacks as well as the threat of new and more destructive futu
7 min read
How to Find Network IP Address of Computer Using Computer Name?
Answer: By using the command "ping" followed by the computer name in the command prompt or terminal.To find the network IP address of a computer using its computer name: Open Command Prompt or Terminal Begin by opening the Command Prompt (Windows) or Terminal (macOS/Linux) on your computer. Use the Ping Command Type "ping" followed by the computer
1 min read
Shortest Path Algorithm in Computer Network
In between sending and receiving data packets from the sender to the receiver, it will go through many routers and subnets. So as a part of increasing the efficiency in routing the data packets and decreasing the traffic, we must find the shortest path. In this article, we are discussing the shortest path algorithms. What is Shortest Path Routing?
6 min read
HMAC Algorithm in Computer Network
HMAC (Hash-based Message Authentication Code) is a type of message authentication code (MAC) that is acquired by executing a cryptographic hash function on the data that is to be authenticated and a secret shared key. Like any of the MACs, it is used for both data integrity and authentication. In this article, we will discuss every point about HMAC
5 min read
Difference between Storage Area Network (SAN) and Network Attached Storage (NAS)
Storage Area Network (SAN) is used for transferring the data between the servers and the storage devices' fiber channels and switches. In SAN (Storage Area Network), data is identified by disk block. Protocols that are used in SAN are SCSI (Small Computer System Interface), SATA (Serial Advanced Technology Attachment), etc. Components of Storage Ar
2 min read
Differences between Wireless Adhoc Network and Wireless Sensor Network
1. Wireless Adhoc Network: A wireless ad-hoc network is a wireless network deployed without any framework or infrastructure. This incorporates wireless mesh networks, mobile ad-hoc networks, and vehicular ad-hoc networks. Its history could be traced back to the Defense Advanced Research Project Agency (DARPA) and Packet Radio Networks (PRNET) which
3 min read
Difference between Next Generation Network and Traditional Network
1. Next Generation Network : In short Next Generation Network is termed as NGN which is packet based network used for both telephony and data. It uses multiple broadband and Quality of Services (QoS) enabled transport technologies to establish advance communication system. NGN can handle multiple type of services/traffic such as voice, audio, video
5 min read
Difference between Software Defined Network and Traditional Network
1. Software Defined Network (SDN) : SDN stands for Software Defined Network which is networking architecture approach. It enables the control and management of network using software applications. Through Software Defined Network (SDN) networking behavior of entire network and its devices are programmed in centrally controlled manner through softwa
5 min read
Difference between Network Administrator and Network Engineer
1. Network Administrator :A network administrator is a someone in an organization whose job is to manage organization's computer network. They also do jobs like on-site server organization , software networking and also placing the network in there correct position which is also called as Network Integrity. Those are the main thing in their job to
3 min read
Difference Between Network Security and Network Administration
In the world of information technology, there are two important and distinct roles that are often confused: network security and network administration. While these two jobs may be closely related, they require different sets of skills and responsibilities. It’s significant to understand the differences between network security and network administ
5 min read
Difference Between Network Management and Network Monitoring
Pre-requisites: Areas of Network Management Network management and Network monitoring are two important functions in maintaining the performance and security of a network. While they are often used interchangeably, they are distinct concepts with different goals and methods. Network management refers to the process of controlling, configuring, and
3 min read
Difference Between Network Congestion and Network Latency
Network congestion refers to a situation in which a network experiences an excessive amount of traffic, resulting in a reduction of available bandwidth and increased delays for network users. This can occur in both wired and wireless networks and can have a significant impact on the performance and reliability of the network. Congestion can occur d
9 min read
Difference Between Network Topology and Network Protocols
Network Topology and Network Protocols are closely related but distinct concepts in the field of computer networking. Network Topology refers to the physical and logical arrangement of devices on a network, while Network Protocols refer to the rules and standards that govern the communication between devices on a network. Understanding the differen
4 min read
How Does a Network Topology Affect Your Decision in Setting up a Network?
Answer: Different Network Topology offer different costs, security, reliability, etc. So we choose one of the network topology as a blueprint for setting up our network according to the features that we required.By Network Topology we get to know how different nodes are connected in the network. There are different types of network topology like Bu
2 min read
How does a Network Interface Card (NIC) Facilitate Connectivity in a Wired Network?
Answer: A network interface card (NIC) facilitates connectivity in a wired network by providing an interface between the physical layer which provides the physical connection with the cables and the data link layer which provides reliable communication channel. The NIC converts the digital data into electrical data so that it can be transferred usi
2 min read
MAC Filtering in Computer Network
There are two kinds of network Adapters. A wired adapter allows us to set up a connection to a modem or router via Ethernet in a computer whereas a wireless adapter identifies and connects to remote hot spots. Each adapter has a distinct label known as a MAC address which recognizes and authenticates the computer. Mac address is shown in the format
10 min read
DHCP Relay Agent in Computer Network
Prerequisite - Dynamic Host Configuration Protocol (DHCP), How DHCP server dynamically assigns IP address to a host? To assign an IP address to the host dynamically, the DHCP client exchanges DHCP messages with the DHCP server in the DORA process. In the DORA process, the discover and request message is broadcast, the offer and the acknowledgement
6 min read
Redundant Link problems in Computer Network
Basically, redundant links are used to prevent nasty network failure. These are used to provide redundancy, i.e back up when a link fails, i.e a frame can be forwarded out through another path but it can cause problems also. Here are some of these problems: Broadcast Storm - A switch forwards out the broadcast frame, generated by another device, to
4 min read
Port Security in Computer Network
Attackers' task is comparatively very easy when they can enter the network they want to attack. Ethernet LANs are very much vulnerable to attack as the switch ports are open to use by default. Various attacks such as Dos attack at layer 2, address spoofing can take place. If the administrator has control over the network then obviously the network
3 min read
EtherChannel in Computer Network
EtherChannel is a port link aggregation technology in which multiple physical port links are grouped into one logical link. It is used to provide high-speed links and redundancy. A maximum of 8 links can be aggregated to form a single logical link. EtherChannel, also known as Link Aggregation Control Protocol (LACP), is a technique used in computer
5 min read
Bit Stuffing in Computer Network
The data link layer is responsible for something called Framing, which is the division of stream of bits from network layer into manageable units (called frames). Frames could be of fixed size or variable size. In variable-size framing, we need a way to define the end of the frame and the beginning of the next frame. Bit stuffing is the insertion o
2 min read
Computer Network | AAA (Authentication, Authorization and Accounting)
The administrator can take access to a router or a device through a console but it is very inconvenient if he is sitting far from the place of that device. So, eventually, he has to take remote access to that device. But as remote access will be available by using an IP address, therefore, it is possible that an unauthorized user can take access us
4 min read
Types of MANET in Computer Network
Prerequisite - MANET: Mobile Ad hoc Network MANET stands for Mobile ad hoc Network also called as wireless ad hoc network or ad hoc wireless network. They consist of a set of mobile nodes connected wirelessly in a self-configured, self-healing network without having a fixed infrastructure. MANET nodes are free to move randomly as the network topolo
12 min read
Redistribution in Computer Network
Often, using a single routing protocol in an organisation is preferred but there are some conditions in which we have to use multi protocol routing. These conditions include multiple administrator running multiple protocols, company mergers or usage of multi-vendors devices. Therefore, we have to advertise a route learned through a routing protocol
5 min read
Type-C Port in Computer Network
Type-C (or USB-C) is a 24-pin USB connector system. This is distinguished by its two-fold rotationally symmetrical connector. The USB Type-C Specification 1.0 was published by the USB Implementers Forum (USB-IF). It was finalized in August 2014. A device that implements USB-C does not necessarily implement USB Power Delivery, USB 3.1, or Alternate
4 min read
Asynchronous Transfer Mode (ATM) in Computer Network
Why ATM networks? Driven by the integration of services and performance requirements of both telephony and data networking: "broadband integrated service vision" (B-ISON). Telephone networks support a single quality of service and are expensive to boot. Internet supports no quality of service but is flexible and cheap. ATM networks were meant to su
5 min read
Puzzle | Eliminating Virus from a Computer Network
In a network of infinitely many computers, 650 computers got infected with certain virus. The IT support team has access to five different types of antivirus software packages (let us call them A, B, C, D and E) that can work on eliminating this virus. Each of the antivirus software packages 'X' can eliminate virus from Xr infected computers if the
3 min read
Elements of Computer Network
Computer Network is a system in which multiple nodes are connected to each other to share information and resources. A computer network allows sharing of resources between different nodes connected within it. Computer Network Elements: The objects basically used in a computer network are known as Computer Network Elements (CNEs). There are basicall
3 min read
three90RightbarBannerImg