Created
January 17, 2020 05:34
-
-
Save mathew-fleisch/57f65c13c7ce2662cc7889d65e6d4742 to your computer and use it in GitHub Desktop.
Rate Limiter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
#class RateLimiter { | |
# public: | |
# // rate is an integer num requests per second | |
# RateLimiter(int rate) { | |
# } | |
# bool IsAllowed() { | |
# //implement this | |
# } | |
# } | |
# Allows 100/sec but also allows bursts of requests up to 150/sec | |
# Optimal solution: Use Token Bucket Alg https://en.wikipedia.org/wiki/Token_bucket | |
# This is not that: | |
MAX_THRESHOLD=100 | |
BURST_THRESHOLD=150 | |
STATE="./state.txt" | |
USER_PREV=0 | |
is_allowed() { | |
# if [ -z "$1" ]; then | |
# echo "missing arg" | |
# exit 1 | |
# fi | |
NUMBER_OF_REQUESTS=$(cat "$STATE" | wc -l) | |
NUMBER_OF_REQUESTS=$((NUMBER_OF_REQUESTS - USER_PREV)) | |
# echo "$NUMBER_OF_REQUESTS" | |
if [[ "$NUMBER_OF_REQUESTS" -lt "$BURST_THRESHOLD" ]]; then | |
if [ "$NUMBER_OF_REQUESTS" -lt "$MAX_THRESHOLD" ]; then | |
USER_PREV=0 | |
fi | |
USER_PREV=$((NUMBER_OF_REQUESTS - MAX_THRESHOLD)) | |
echo "1" | |
exit 0 | |
else | |
echo "0" | |
fi | |
USER_PREV=0 | |
} | |
# token bucket alg | |
for req in $(seq 1 100); do | |
# echo "$RANDOM" | |
MAX=$((1 + RANDOM % 150)) | |
echo "Req: $MAX" | |
rm -rf "$STATE" | |
touch "$STATE" | |
for req in $(seq 1 $MAX); do | |
echo "$req" >> "$STATE" | |
done | |
isAllowed=$(is_allowed) | |
echo "is Allowed: $isAllowed" | |
done | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment