š„Letās Do DevOps: Building an API Token Expired Circuit Breaker
--
This blog series focuses on presenting complex DevOps projects as simple and approachable via plain language and lots of pictures. You can do it!
Hey all!
I recently had to create 60k auto-link references in Jira (link to the story), and I immediately ran into an issue ā a GitHub PAT (Personal Access Token) is given 5,000 ātokensā per hour. A ātokenā is a budget of the API calls that can be issued to the server which will be honored. More than that will fail.
API budgets are a concept established to help avoid DoS (Denial of Service) attacks where tens or hundreds of thousands of calls are sent to a service in order to destabilize it.
Well, sending 60k requests to GitHub means Iām spending 60k tokens, 12 times the value I get per hour. My local script runs quite a bit faster than that, uh oh. And many of the other requests Iām sending, like opening PRs and issuing comments on them, also consume tokens ā so how can I tell when my API token budget is consumed? How can I tell when token budget has been refilled and I can continue?
Thatās where a ācircuit breakerā comes in. That concept is borrowed from electrical engineering where it means to detect when more current than is safe passes through the circuit breaker, and when that happens it immediately disconnects the circuit so nothing downstream of it can be fried. In this context, it means weāll monitor our API token budget, and establish a wait timer until our budget is refilled.
Letās do it!
Establish the Circuit Breaker
A circuit breaker in this context is a check that wonāt continue until a condition is satisfied. We might want to call this circuit breaker lots of times, so letās put it in a function called hold_until_rate_limit_success
.
And then we build one of the āyou shouldnāt do thisā loops, a while true
, which means our loop will continue forever until a command issues break
. These are generally not advised because a misconfiguration could lead to a loop that goes on forever. Weāll keep our function concise and simple in order to be as safe as possible.