The Wayback Machine - https://web.archive.org/web/20240910010403/https://www.geeksforgeeks.org/berkeleys-algorithm/
Open In App

Berkeley’s Algorithm

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

Berkeley’s Algorithm is a clock synchronization technique used in distributed systems. The algorithm assumes that each machine node in the network either doesn’t have an accurate time source or doesn’t possess a UTC server.
Algorithm 
1) An individual node is chosen as the master node from a pool node in the network. This node is the main node in the network which acts as a master and the rest of the nodes act as slaves. The master node is chosen using an election process/leader election algorithm.
2) Master node periodically pings slaves nodes and fetches clock time at them using Cristian’s algorithm.
The diagram below illustrates how the master sends requests to slave nodes. 
 

Ping for time at client side

The diagram below illustrates how slave nodes send back time given by their system clock. 
 

Receive time from slaves/clients

3) Master node calculates the average time difference between all the clock times received and the clock time given by the master’s system clock itself. This average time difference is added to the current time at the master’s system clock and broadcasted over the network.
Pseudocode for above step: 
 

 

The diagram below illustrates the last step of Berkeley’s algorithm. 
 

Send back synchronized to slaves

Scope of Improvement 
 

  • Improvision inaccuracy of Cristian’s algorithm.
  • Ignoring significant outliers in the calculation of average time difference
  • In case the master node fails/corrupts, a secondary leader must be ready/pre-chosen to take the place of the master node to reduce downtime caused due to the master’s unavailability.
  • Instead of sending the synchronized time, master broadcasts relative inverse time difference, which leads to a decrease in latency induced by traversal time in the network while the time of calculation at slave node.

 features of Berkeley’s Algorithm:

Centralized time coordinator: Berkeley’s Algorithm uses a centralized time coordinator, which is responsible for maintaining the global time and distributing it to all the client machines.

Clock adjustment: The algorithm adjusts the clock of each client machine based on the difference between its local time and the time received from the time coordinator.

Average calculation: The algorithm calculates the average time difference between the client machines and the time coordinator to reduce the effect of any clock drift.

Fault tolerance: Berkeley’s Algorithm is fault-tolerant, as it can handle failures in the network or the time coordinator by using backup time coordinators.

Accuracy: The algorithm provides accurate time synchronization across all the client machines, reducing the chances of errors due to time discrepancies.

Scalability: The algorithm is scalable, as it can handle a large number of client machines, and the time coordinator can be easily replicated to provide high availability.

Security: Berkeley’s Algorithm provides security mechanisms such as authentication and encryption to protect the time information from unauthorized access or tampering.

The code below is a python script that can be used to trigger a master clock server. 
 

Python3




# Python3 program imitating a clock server
 
from functools import reduce
from dateutil import parser
import threading
import datetime
import socket
import time
 
 
# datastructure used to store client address and clock data
client_data = {}
 
 
''' nested thread function used to receive
    clock time from a connected client '''
def startReceivingClockTime(connector, address):
 
    while True:
        # receive clock time
        clock_time_string = connector.recv(1024).decode()
        clock_time = parser.parse(clock_time_string)
        clock_time_diff = datetime.datetime.now() - \
                                                 clock_time
 
        client_data[address] = {
                       "clock_time"      : clock_time,
                       "time_difference" : clock_time_diff,
                       "connector"       : connector
                       }
 
        print("Client Data updated with: "+ str(address),
                                              end = "\n\n")
        time.sleep(5)
 
 
''' master thread function used to open portal for
    accepting clients over given port '''
def startConnecting(master_server):
     
    # fetch clock time at slaves / clients
    while True:
        # accepting a client / slave clock client
        master_slave_connector, addr = master_server.accept()
        slave_address = str(addr[0]) + ":" + str(addr[1])
 
        print(slave_address + " got connected successfully")
 
        current_thread = threading.Thread(
                         target = startReceivingClockTime,
                         args = (master_slave_connector,
                                           slave_address, ))
        current_thread.start()
 
 
# subroutine function used to fetch average clock difference
def getAverageClockDiff():
 
    current_client_data = client_data.copy()
 
    time_difference_list = list(client['time_difference']
                                for client_addr, client
                                    in client_data.items())
                                    
 
    sum_of_clock_difference = sum(time_difference_list, \
                                   datetime.timedelta(0, 0))
 
    average_clock_difference = sum_of_clock_difference \
                                         / len(client_data)
 
    return  average_clock_difference
 
 
''' master sync thread function used to generate
    cycles of clock synchronization in the network '''
def synchronizeAllClocks():
 
    while True:
 
        print("New synchronization cycle started.")
        print("Number of clients to be synchronized: " + \
                                     str(len(client_data)))
 
        if len(client_data) > 0:
 
            average_clock_difference = getAverageClockDiff()
 
            for client_addr, client in client_data.items():
                try:
                    synchronized_time = \
                         datetime.datetime.now() + \
                                    average_clock_difference
 
                    client['connector'].send(str(
                               synchronized_time).encode())
 
                except Exception as e:
                    print("Something went wrong while " + \
                          "sending synchronized time " + \
                          "through " + str(client_addr))
 
        else :
            print("No client data." + \
                        " Synchronization not applicable.")
 
        print("\n\n")
 
        time.sleep(5)
 
 
# function used to initiate the Clock Server / Master Node
def initiateClockServer(port = 8080):
 
    master_server = socket.socket()
    master_server.setsockopt(socket.SOL_SOCKET,
                                   socket.SO_REUSEADDR, 1)
 
    print("Socket at master node created successfully\n")
       
    master_server.bind(('', port))
 
    # Start listening to requests
    master_server.listen(10)
    print("Clock server started...\n")
 
    # start making connections
    print("Starting to make connections...\n")
    master_thread = threading.Thread(
                        target = startConnecting,
                        args = (master_server, ))
    master_thread.start()
 
    # start synchronization
    print("Starting synchronization parallelly...\n")
    sync_thread = threading.Thread(
                          target = synchronizeAllClocks,
                          args = ())
    sync_thread.start()
 
 
 
# Driver function
if __name__ == '__main__':
 
    # Trigger the Clock Server
    initiateClockServer(port = 8080)


Output: 
 

New synchronization cycle started.
Number of clients to be synchronized: 3

Client Data updated with: 127.0.0.1:57284

Client Data updated with: 127.0.0.1:57274

Client Data updated with: 127.0.0.1:57272

The code below is a python script that can be used to trigger a slave/client. 
 

Python3




# Python3 program imitating a client process
 
from timeit import default_timer as timer
from dateutil import parser
import threading
import datetime
import socket
import time
 
 
# client thread function used to send time at client side
def startSendingTime(slave_client):
 
    while True:
        # provide server with clock time at the client
        slave_client.send(str(
                       datetime.datetime.now()).encode())
 
        print("Recent time sent successfully",
                                          end = "\n\n")
        time.sleep(5)
 
 
# client thread function used to receive synchronized time
def startReceivingTime(slave_client):
 
    while True:
        # receive data from the server
        Synchronized_time = parser.parse(
                          slave_client.recv(1024).decode())
 
        print("Synchronized time at the client is: " + \
                                    str(Synchronized_time),
                                    end = "\n\n")
 
 
# function used to Synchronize client process time
def initiateSlaveClient(port = 8080):
 
    slave_client = socket.socket()         
       
    # connect to the clock server on local computer
    slave_client.connect(('127.0.0.1', port))
 
    # start sending time to server
    print("Starting to receive time from server\n")
    send_time_thread = threading.Thread(
                      target = startSendingTime,
                      args = (slave_client, ))
    send_time_thread.start()
 
 
    # start receiving synchronized from server
    print("Starting to receiving " + \
                         "synchronized time from server\n")
    receive_time_thread = threading.Thread(
                       target = startReceivingTime,
                       args = (slave_client, ))
    receive_time_thread.start()
 
 
# Driver function
if __name__ == '__main__':
 
    # initialize the Slave / Client
    initiateSlaveClient(port = 8080)


Output: 
 

Recent time sent successfully
Synchronized time at the client is: 2018-11-23 18:49:31.166449

Below is a screenshot of the runtime of the above python scripts where the top left console represents the master thread while others represent slave threads. 
 

Berkley Algorithm imitation

 

Note: The scripts above closely depicts working of Berkley’s Algorithm but may differ from the actual implementation of the algorithm in production based distributed networking systems. Availability of port 8080 is machine dependent. In case port 8080 is not free, change the port number accordingly in both master and slave scripts. 

References: 
 

  1. https://en.wikipedia.org/wiki/Berkeley_algorithm
  2. https://www.geeksforgeeks.org/socket-programming-multi-threading-python/
  3. https://www.geeksforgeeks.org/cristians-algorithm/

 



Previous Article
Next Article

Similar Reads

Edge Relaxation Property for Dijkstra’s Algorithm and Bellman Ford's Algorithm
In the field of graph theory, various shortest path algorithms especially Dijkstra’s algorithm and Bellmann-Ford’s algorithm repeatedly employ the use of the technique called Edge Relaxation. The idea of relaxation is the same in both algorithms and it is by understanding, the 'Relaxation property' we can fully grasp the working of the two algorith
4 min read
Difference between Greedy Algorithm and Divide and Conquer Algorithm
Greedy algorithm and divide and conquer algorithm are two common algorithmic paradigms used to solve problems. The main difference between them lies in their approach to solving problems. Greedy Algorithm:The greedy algorithm is an algorithmic paradigm that follows the problem-solving heuristic of making the locally optimal choice at each stage wit
3 min read
Algorithm Library | C++ Magicians STL Algorithm
For all those who aspire to excel in competitive programming, only having a knowledge about containers of STL is of less use till one is not aware what all STL has to offer. STL has an ocean of algorithms, for all < algorithm > library functions : Refer here.Some of the most used algorithms on vectors and most useful one's in Competitive Prog
7 min read
What is the stupidest sorting algorithm? (Worst Sorting Algorithm)
Bogo sort stands out as the undisputed champion of stupidity. Unlike other sorting algorithms that follow a structured approach, Bogo sort relies on sheer luck and randomness to achieve its goal. How Bogo Sort Works?Bogo sort operates on the following principle: Randomly shuffle the elements in the list.Check if the list is sorted.If the list is no
2 min read
Difference Between Dijkstra's Algorithm and A* Search Algorithm
Dijkstra's Algorithm and A* Algorithm are two of the most widely used techniques. Both are employed to the find the shortest path between the nodes in a graph but they have distinct differences in their approaches and applications. Understanding these differences is crucial for the selecting the appropriate algorithm for the given problem. What is
3 min read
Z algorithm (Linear time pattern searching Algorithm)
This algorithm efficiently locates all instances of a specific pattern within a text in linear time. If the length of the text is "n" and the length of the pattern is "m," then the total time taken is O(m + n), with a linear auxiliary space. It is worth noting that the time and auxiliary space of this algorithm is the same as the KMP algorithm, but
13 min read
Karatsuba algorithm for fast multiplication using Divide and Conquer algorithm
Given two binary strings that represent value of two integers, find the product of two strings. For example, if the first bit string is "1100" and second bit string is "1010", output should be 120. For simplicity, let the length of two strings be same and be n. A Naive Approach is to follow the process we study in school. One by one take all bits o
15+ min read
Reversal algorithm for Array rotation
Given an array arr[] of size N, the task is to rotate the array by d position to the left. Examples: Input: arr[] = {1, 2, 3, 4, 5, 6, 7}, d = 2Output: 3, 4, 5, 6, 7, 1, 2Explanation: If the array is rotated by 1 position to the left, it becomes {2, 3, 4, 5, 6, 7, 1}.When it is rotated further by 1 position,it becomes: {3, 4, 5, 6, 7, 1, 2} Input:
15 min read
Block swap algorithm for array rotation
Write a function rotate(arr[], d, n) that rotates arr[] of size n by d elements. Rotation of the above array by 2 will make an array Algorithm : Initialize A = arr[0..d-1] and B = arr[d..n-1] 1) Do following until size of A is equal to size of B a) If A is shorter, divide B into Bl and Br such that Br is of same length as A. Swap A and Br to change
15+ min read
Boruvka's algorithm for Minimum Spanning Tree
Following two algorithms are generally taught for Minimum Spanning Tree (MST) problem. Prim's algorithm Kruskal's algorithm There is a third algorithm called Boruvka's algorithm for MST which (like the above two) is also Greedy algorithm. The Boruvka's algorithm is the oldest minimum spanning tree algorithm was discovered by Boruvka in 1926, long b
1 min read
Introduction to Push Relabel Algorithm
Given a graph which represents a flow network where every edge has a capacity. Also given two vertices source ‘s’ and sink ‘t’ in the graph, find the maximum possible flow from s to t with following constraints: Flow on an edge doesn’t exceed the given capacity of the edge. Incoming flow is equal to outgoing flow for every vertex except s and t. Fo
6 min read
An in-place algorithm for String Transformation
Given a string, move all even positioned elements to the end of the string. While moving elements, keep the relative order of all even positioned and odd positioned elements the same. For example, if the given string is "a1b2c3d4e5f6g7h8i9j1k2l3m4", convert it to "abcdefghijklm1234567891234" in-place and in O(n) time complexity. Below are the steps
15+ min read
Union By Rank and Path Compression in Union-Find Algorithm
In the previous post, we introduced union find algorithm and used it to detect cycles in a graph. We used the following union() and find() operations for subsets. C/C++ Code // Naive implementation of find int find(int parent[], int i) { if (parent[i] == -1) return i; return find(parent, parent[i]); } // Naive implementation of union() void Union(i
15+ min read
Closest Pair of Points using Divide and Conquer algorithm
We are given an array of n points in the plane, and the problem is to find out the closest pair of points in the array. This problem arises in a number of applications. For example, in air-traffic control, you may want to monitor planes that come too close together, since this may indicate a possible collision. Recall the following formula for dist
15+ min read
Fleury's Algorithm for printing Eulerian Path or Circuit
Eulerian Path is a path in a graph that visits every edge exactly once. Eulerian Circuit is an Eulerian Path that starts and ends on the same vertex. We strongly recommend first reading the following post on Euler Path and Circuit. "https://www.cdn.geeksforgeeks.org/eulerian-path-and-circuit/" In the above-mentioned post, we discussed the problem o
15+ min read
Manacher's Algorithm - Linear Time Longest Palindromic Substring - Part 3
In Manacher's Algorithm Part 1 and Part 2, we gone through some of the basics, understood LPS length array and how to calculate it efficiently based on four cases. Here we will implement the same.We have seen that there are no new character comparison needed in case 1 and case 2. In case 3 and case 4, necessary new comparison are needed. In followi
15+ min read
Boruvka's algorithm | Greedy Algo-9
We have discussed the following topics on Minimum Spanning Tree.Applications of Minimum Spanning Tree Problem Kruskal’s Minimum Spanning Tree Algorithm Prim’s Minimum Spanning Tree AlgorithmIn this post, Boruvka's algorithm is discussed. Like Prim's and Kruskal's, Boruvka’s algorithm is also a Greedy algorithm. Below is a complete algorithm. 1) Inp
15+ min read
Analysis and applications Karger’s algorithm for Minimum Cut
We have introduced and discussed below Karger's algorithm in set 1. 1) Initialize contracted graph CG as copy of original graph 2) While there are more than 2 vertices. a) Pick a random edge (u, v) in the contracted graph. b) Merge (or contract) u and v into a single vertex (update the contracted graph). c) Remove self-loops 3) Return cut represent
4 min read
Hopcroft–Karp Algorithm for Maximum Matching | Set 1 (Introduction)
A matching in a Bipartite Graph is a set of the edges chosen in such a way that no two edges share an endpoint. A maximum matching is a matching of maximum size (maximum number of edges). In a maximum matching, if any edge is added to it, it is no longer a matching. There can be more than one maximum matching for a given Bipartite Graph. We have di
3 min read
Jump Pointer Algorithm
The Jump pointer algorithm is a design technique for parallel algorithms that operate on pointer structures, such as arrays or linked list. This algorithm is normally used to determine the root of the forest of a rooted tree. In the jump pointer algorithm, we pre-process a tree so that one can able to answer the queries to find any parent of any no
15+ min read
Optimal Page Replacement Algorithm
Prerequisite: Page Replacement Algorithms In operating systems, whenever a new page is referred and not present in memory, page fault occurs and Operating System replaces one of the existing pages with newly needed page. Different page replacement algorithms suggest different ways to decide which page to replace. The target for all algorithms is to
15+ min read
Move To Front Data Transform Algorithm
What is the MTF transform? The MTF (Move to Front) is a data transformation algorithm that restructures data in such a way that the transformed message is more compressible and therefore used as an extra step in compression. Technically, it is an invertible transform of a sequence of input characters to an array of output numbers. Why MTF? In many
9 min read
Union-Find Algorithm | (Union By Rank and Find by Optimized Path Compression)
Check whether a given graph contains a cycle or not. Example: Input: Output: Graph contains Cycle. Input: Output: Graph does not contain Cycle. Prerequisites: Disjoint Set (Or Union-Find), Union By Rank and Path CompressionWe have already discussed union-find to detect cycle. Here we discuss find by path compression, where it is slightly modified t
13 min read
XOR Basis Algorithm
The XOR operation between two numbers P and Q can be looked in a different way as the bitwise sum modulo 2 on the bits of P and Q. Consider P = 10010 and Q = 00110. Starting from leftmost, we verify the above statement : (1 + 0) % 2 = 1 (0 + 0) % 2 = 0 (0 + 1) % 2 = 1 (1 + 1) % 2 = 0 (0 + 0) % 2 = 0 A binary number is in the form of a ℤ2d vector wh
9 min read
Banker's Algorithm in Operating System
Prerequisite - Resource Allocation Graph (RAG), Banker’s Algorithm, Program for Banker’s Algorithm Banker's Algorithm is a resource allocation and deadlock avoidance algorithm. This algorithm test for safety simulating the allocation for predetermined maximum possible amounts of all resources, then makes an “s-state” check to test for possible acti
15 min read
BFS using vectors & queue as per the algorithm of CLRS
Breadth-first search traversal of a graph using the algorithm given in CLRS book. BFS is one of the ways to traverse a graph. It is named so because it expands the frontier between discovered and undiscovered vertices uniformly across the breadth of the frontier. What it means is that the algorithm first discovers all the vertices connected to "u"
11 min read
Tomohiko Sakamoto's Algorithm- Finding the day of the week
Given any date according to the Gregorian Calendar, the task is to return the day(Monday, Tuesday...etc) on that particular day. Examples: Input : Date: 13 July 2017 [13.07.2017] Output : 4 i.e Thursday Input : Date: 15 August 2012 [15.08.2012] Output : 3 i.e Wednesday Input : Date: 24 December 2456 [24.12.2456] Output : 0 i.e Sunday Although there
6 min read
Freivald’s Algorithm to check if a matrix is product of two
Given three matrices A, B and C, find if C is a product of A and B. Examples: Input : A = 1 1 1 1 B = 1 1 1 1 C = 2 2 2 2 Output : Yes C = A x B Input : A = 1 1 1 1 1 1 1 1 1 B = 1 1 1 1 1 1 1 1 1 C = 3 3 3 3 1 2 3 3 3 Output : No A simple solution is to find product of A and B and then check if product is equal to C or not. A possible time complex
12 min read
Probabilistic shortest path routing algorithm for optical networks
Data transfer operations is a crucial aspect in case of networking and routing. So efficient data transfer operations is a must need, with minimum hardware cost (Optical Cables, WDM Network components, Decoders, Multiplexers) and also in the minimum time possible. Thus, the need is to propose an algorithm that finds the shortest path between two no
5 min read
RSA Algorithm using Multiple Precision Arithmetic Library
Public Key Cryptography is also known as Asymmetric Cryptography is the type of cryptography which involves the usage of two keys namely Public Key and Private Key. The Public Key of the receiver is used to encrypt the plaintext by the sender while the Private Key of the receiver is used to decrypt the encrypted message and hence can be decrypted o
4 min read