Skip to content

Instantly share code, notes, and snippets.

@schoren
Last active October 30, 2023 13:51
Show Gist options
  • Save schoren/5dd4dcadf133e4c56fa20c0b6a8d67ef to your computer and use it in GitHub Desktop.
Save schoren/5dd4dcadf133e4c56fa20c0b6a8d67ef to your computer and use it in GitHub Desktop.
Script to calculate max attempts for an exponential backoff retry strategy
#!/bin/bash
# Usage: ./calculate_max_time.sh <initial_backoff> <backoff_multiplier> <max_backoff> <max_total_time>
# Command line arguments
initial_backoff=$1
backoff_multiplier=$2
max_backoff=$3
max_total_time=$4
# Initializing variables
total_time=0.0
attempt=0
# Function to calculate backoff time for a given attempt
function calculate_backoff_time {
local attempt=$1
echo $(awk -v initial_backoff=$initial_backoff -v backoff_multiplier=$backoff_multiplier -v attempt=$attempt \
'BEGIN {print (initial_backoff * (backoff_multiplier ^ (attempt - 1)))}')
}
# Loop to calculate total time spent in retries
while (( $(echo "$total_time < $max_total_time" | bc -l) ))
do
# Incrementing the number of attempts
attempt=$((attempt + 1))
# Calculating backoff time for this attempt
backoff_time=$(calculate_backoff_time $attempt)
# Using the minimum of backoff_time and max_backoff
backoff_time=$(awk -v backoff_time=$backoff_time -v max_backoff=$max_backoff 'BEGIN {print (backoff_time < max_backoff ? backoff_time : max_backoff)}')
# Adding backoff_time to total_time
total_time=$(awk -v total_time=$total_time -v backoff_time=$backoff_time 'BEGIN {print total_time + backoff_time}')
# Printing the timeline of retries
echo "Attempt $attempt at $(awk -v total_time=$total_time 'BEGIN {print total_time}') seconds, Backoff Time: $backoff_time seconds"
done
# Printing the input values
echo -e "\nParameter\t\tValue"
echo -e "Initial Backoff\t\t$initial_backoff seconds"
echo -e "Backoff Multiplier\t$backoff_multiplier"
echo -e "Max Backoff\t\t$max_backoff seconds"
echo -e "Max Total Time\t\t$max_total_time seconds"
echo ""
# Printing the results in a more prominent format
echo "####################### RESULTS #######################"
printf "Maximum Attempts:\t%4d\n" $attempt
printf "Total Time:\t\t%7.2f seconds\n" $total_time
echo "######################################################"
@schoren
Copy link
Author

schoren commented Oct 30, 2023

Use without download:

curl -SL https://gist.githubusercontent.com/schoren/5dd4dcadf133e4c56fa20c0b6a8d67ef/raw/4df471d8d603be7a82a5c2c99284bcb4cf2f760e/calculate_max_time.sh | bash -s  -- <initial_backoff> <backoff_multiplier> <max_backoff> <max_total_time>

Example:

curl -SL https://gist.githubusercontent.com/schoren/5dd4dcadf133e4c56fa20c0b6a8d67ef/raw/4df471d8d603be7a82a5c2c99284bcb4cf2f760e/calculate_max_time.sh | bash -s  -- 0.1 2.0 5.0 120

Screenshot 2023-10-30 at 10 51 02

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment