RobotEvents API v2 Rate Limit Documentation

Does anyone have documentation or self-discovered information about the rate limiting on the RobotEvents API?

From what I can tell, it’s incredibly non-standard (e.g. returning 403s instead of 429s) and doesn’t provide any headers on responses that might give an indication as to what the rate limit is or what is left, or when it would reset.

I’m close to doing some experimentation to try and figure the parameters of the limiting out, but I’d rather not re-invent the wheel if there’s info somewhere that I haven’t been able to find.

I have been on the hunt for the same information and have failed to find any documentation. If you conducted the experimentation I would love to know the results. The API does, as you said, appear to be incredibly non standard.

I have created an experiment with 6 trials - one per day.

First trial starts at 5, second trial 4, and so forth with the 6th trial at 0.

For each trial, it will call robotevents for its page every ‘n’ seconds for 12 hours.

If there is a status code other than 200, the trail stops for the day.

My Code
# .venv/bin/python main.py > output.log 2>&1 & disown

import requests
import time

with open("TOKEN", "r") as f:
    API_TOKEN = f.read().strip()

url = "https://www.robotevents.com/api/v2/events"
headers = {
    "Authorization": f"Bearer {API_TOKEN}",
    "Accept": "application/json",
}

params = {
    "page": 1,
    "per_page": 25,
}


def call_robotevents(file_name, seconds_elapsed):
    start_time = time.time()
    
    try:
        response = requests.get(url, headers=headers, params=params, timeout=15)
        status_code = response.status_code
    except requests.RequestException: # If there are any issues, use -1 as status code
        status_code = -1
    
    process_time = time.time() - start_time 
    
    # Document status code, seconds elapsed, and process time
    with open(file_name, "a") as f:
        f.write(f"{seconds_elapsed:.2f}, {status_code}, {process_time:.2f}\n")
        
    return status_code, process_time # Return status code and process time

def create_csv_file(file_name):
    # Write CSV header once for this file
    with open(file_name, "w") as f:
        f.write("seconds_elapsed, status_code, process_time\n")

SECONDS_BETWEEN_CALL_START = 5
TIME_BETWEEN_RUNS_SECONDS = 25 * 60 * 60 # ONE DAY + 1 HOUR
TIME_TO_GIVE_UP_SECONDS = 12 * 60 * 60 # HALF A DAY

seconds_between_call = SECONDS_BETWEEN_CALL_START
while seconds_between_call > 0:    
    
    file_name = f"{seconds_between_call}_seconds_between_calls.csv"
    create_csv_file(file_name)

        
    start_time = time.time()
    seconds_elapsed = 0
    status_code = 200
    while seconds_elapsed < TIME_BETWEEN_RUNS_SECONDS:
        seconds_elapsed = time.time() - start_time # Get number of seconds for each run
        
        # If the API gave out or we are done, then just wait the remaining time
        if seconds_elapsed > TIME_TO_GIVE_UP_SECONDS or status_code != 200:
            remaining = max(TIME_BETWEEN_RUNS_SECONDS - seconds_elapsed, 0)
            time.sleep(remaining)
            break
        
        status_code, process_time = call_robotevents(file_name, seconds_elapsed)
        
        # Wait period of time before the next call
        wait_time = max(seconds_between_call - process_time, 0)
        time.sleep(wait_time)
    
    seconds_between_call -= 1

In a week from now, this should be able to start giving us answers.

Expect .csv files of the results and charts a week from now. :slight_smile:

I am by no means a software developer, so this could be a cognitive failure on my part, but my limited experience with the RobotEvents API rate limit seems inconsistent. I’ve spent some time this year developing my (very bad) web application to give me data-driven talking points when I commentate matches at Worlds.

During development, it looked like I would sometimes get rate limited on a few API requests and then somehow avoid a rate limit an hour later with far more requests. One thing I did notice was what seemed to be a “timeout.” If I got rate limited, it felt like my API key would “freeze” for a short period of time, no matter how many requests were made. Of course, I know approximately nothing about software.

One thing I did notice was that a lot of the endpoints seem to require an N+1 query (in other words: you don’t start with the id of the Team, so you have to get that ID before you can request, for example, rankings). The first thing I do is save all the teamIDs from a given event (which, I think, also requires an N+1 query).

@brendanmcguire (whose IQ makes mine look like a 404 error) might have some thoughts on the question regarding rate limits. He developed the tm-switcher application, RefereeFYI, and the robotevents API interaction module.

While waiting on the rate limit stuff to process, I want to talk about the network based on what I am learning.

Looking here, https://www.nslookup.io/domains/robotevents.com/webservers/

Whenever you go to www.robotevents.com, it returns Cloudflare’s ip addresses in Florida 104.18.40.111and California 172.64.147.145. So if I ping RobotEvents, I will only get a response cycle times from my server to one of CloudFlare’s servers and back.

Pinging from My Computer → CloudFlare California → My Computer


Min Process Time Q1 Process Time Median Process Time Q3 Process Time Max Process Time Average Process Time Standard Deviation
0.02 0.03 0.03 0.04 0.17 0.04 0.03

Pinging from My Computer → CloudFlare Florida → My Computer


Min Process Time Q1 Process Time Median Process Time Q3 Process Time Max Process Time Average Process Time Standard Deviation
0.02 0.08 0.08 0.11 0.20 0.08 0.04

So location affects the downtime quite drastically with CloudFlare servers adding a relatively considerable amount of delay. If packets are sent in larger amounts, cloudflare might add more delay due to higher processing requirements.

Firstly, RobotEvents is masked by CloudFlare so the closest thing would to be seeing the time for a request return from https://www.robotevents.com/api/v2/swagger.yml. This will be the closest baseline I can get to a ping, given that I am not really able to ping the actual server for RobotEvents. → This will be necessary to see how much of the time to process is looking into the RobotEvents database when compared to the network itself, as geographic locations make the times to receive information vary.

Swagger rough ping estimate of My Computer → CloudFlare Servers → RobotEvents Servers → CloudFlare Servers → My Computer

Min Process Time Q1 Process Time Median Process Time Q3 Process Time Max Process Time Average Process Time Standard Deviation
0.0755 0.0831 0.0831 0.0854 0.1499 0.0847 0.0091

Personally, I believe above show a good baseline. It isn’t actual ping, but it lets us know the database access and process time.

After 8639 requests, with a delay of 5 seconds between requests (inclusively and not exclusively delayed), calling https://www.robotevents.com/api/v2/events.


Min Process Time Q1 Process Time Median Process Time Q3 Process Time Max Process Time Average Process Time Standard Deviation
0.58 0.63 0.63 0.65 2.76 0.64 0.05

From this, we can find a relative estimate on dabase processing time on RobotEvent’s side via Time To List Events - Swagger Time in seconds.

Median Database Processing Time Average Database Processing Time
0.5470 0.5539

This seems like database retreival takes some time from RobotEvents side, and should be factored in with your programs that taps into RobotEvents API.

So, a TL;DR:

  1. When making an API call, it takes around 0.58 seconds to receive a message.
  2. When accessing data, it takes around 0.08 seconds for network communication and 0.55 seconds for RobotEvents to process a database query roughly.
  3. These times may vary based on what is requested, but the bottleneck is very much database retreival.
  4. For 12 hours, I ran code that made an API call every 5 seconds, and none of them returned a status other than 200 (essentially, no issues or push-backs). → 8639 requests were made yesterday
  5. I will keep posted about the future, to see how RobotEvents handles calls every 4, 3, 2, and 1 seconds.

Now there appears to be a gauranteed safe zone. And with time we can hone in on how close we can make this ‘safe zone’ of API calls be, in a couple more days. :slight_smile:

I think a lot of this is down to the API being built for the needs of RobotEvents and not as a general-purpose API for accessing the data.

Take my current project for example. I’m pulling historical data for our club, so while RobotEvents & the API treat the Team Number as the distinct unit for Team (which we have 38 of between IQ & V5), for my purposes it’s the Team Number + the Season (which we have 131 of) because I want to gather season-by-season stats. What makes this extra tricky is trying to get the name that goes with a given team number earlier than the last season it was active. To do that, I have to:

  1. Get the list of Team IDs based on the Team Numbers
  2. Get and loop through all the Events each team participated in to see which seasons they were active. (I manage to do this with one API call and more processing on my end)
  3. Loop through the list of active seasons for each team (i.e. 131 times), getting the Team’s Events for that season
  4. Calling the /event/{id}/teams endpoint for the first event in that list to get the name the team used that season (again, 131 times)

It takes nearly 10 minutes to do all that, but 8.5 of those minutes were sleeping when I hit the rate limit.

Not sure about anyone else’s experience, but shortly after this posted I started consistently seeing Cloudflare-served 429 errors, and I’ve been able to have back-off code work for me. That means I can have something functional at least, but it’d be nice to know what the limits are so I can make a more informed effort to avoid them.

Here is some of the python code I use for vrc-data-analysis.com (which will be retiring after Worlds this year).

def _get_robotevents_data(the_url, max_attempts=6, min_delay=65, delay_increment=10):
    def _redact_headers(h):
        try:
            if h is None:
                return None
            if not isinstance(h, dict):
                return h
            hr = dict(h)
            if "Authorization" in hr:
                hr["Authorization"] = "Bearer ***REDACTED***"
            return hr
        except Exception:
            return {"Authorization": "Bearer ***REDACTED***"}

    df_retval = None
    got_data = False
    num_attempts = 0

    while num_attempts < max_attempts and got_data == False:
        use_header = random.choice(
            ALL_ROBOTEVENTS_HEADERS
        )  # Randomly selects equal probability
        try:
            response = requests.get(the_url, headers=use_header)
            if response.status_code == 429:  # Rate limited
                current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                print(
                    f"\tRate limited at {current_time}, raising exception....",
                    flush=True,
                )
                raise Exception(
                    f"Rate limited at {current_time} on request to {the_url} with header {str(_redact_headers(use_header))}"
                )

            json_results = json.loads(response.content.decode("utf-8", "ignore"))
        except Exception as e:
            stack_trace = traceback.format_exc()
            print(f"Exception in _get_robotevents_data: {str(e)}", flush=True)
            num_attempts = num_attempts + 1
            if num_attempts < max_attempts:
                time.sleep(min_delay + (num_attempts) * delay_increment)
            continue

        try:
            df_retval = pd.read_json(StringIO(json.dumps(json_results["data"])))
            got_data = True
        except Exception as e:
            num_attempts = num_attempts + 1
            print(
                "Exception " + str(e) + " with response: " + json.dumps(json_results),
                flush=True,
            )
            if num_attempts < max_attempts:
                time.sleep((num_attempts) * delay_increment)

    if got_data:
        while json_results["meta"]["next_page_url"] is not None:
            got_data = False
            while num_attempts < max_attempts and got_data == False:
                use_header = random.choice(
                    ALL_ROBOTEVENTS_HEADERS
                )  # Randomly selects equal probability
                try:
                    response = requests.get(
                        json_results["meta"]["next_page_url"], headers=use_header
                    )
                    if response.status_code == 429:  # Rate limited
                        current_time = datetime.datetime.now().strftime(
                            "%Y-%m-%d %H:%M:%S"
                        )
                        print(
                            f"\tRate limited at {current_time}, raising exception....",
                            flush=True,
                        )
                        raise Exception(
                            f"Rate limited on request to {json_results['meta']['next_page_url']} with header {str(_redact_headers(use_header))}"
                        )

                    json_results = json.loads(
                        response.content.decode("utf-8", "ignore")
                    )
                except:
                    json_results = dict()

                if "data" in json_results.keys():
                    result_json = json.dumps(json_results["data"])
                    df_thispage = pd.read_json(StringIO(result_json))
                    df_retval = pd.concat([df_retval, df_thispage])
                    got_data = True
                else:
                    current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                    print(
                        f"At {current_time} no element 'data' in response: "
                        + json.dumps(json_results),
                        flush=True,
                    )
                    print("\tHTTP Response: " + str(response), flush=True)
                    print(
                        "\tHTTP Response Headers: " + str(response.headers), flush=True
                    )
                    print(
                        "\tHTTP Response Headers: " + str(response.headers), flush=True
                    )
                    num_attempts = num_attempts + 1
                    if num_attempts >= max_attempts:
                        raise Exception(
                            "No element 'data' in RobotEvents response after "
                            + str(num_attempts)
                            + " attempts."
                        )
                    else:
                        print(f"\tHeader: {str(use_header)}", flush=True)
                        print(
                            "Waiting "
                            + str(min_delay + (num_attempts) * delay_increment)
                            + " seconds for next pull request",
                            flush=True,
                        )
                        time.sleep(min_delay + (num_attempts) * delay_increment)
    else:
        raise Exception("Unable to get data.")
    return df_retval

Which I’ll then call from other functions:

def get_event_matches_by_division(
    event_id, division_id, max_attempts=4, min_delay=65, delay_increment=15
):
    return _get_robotevents_data(
        ROBOT_EVENTS_EVENT_GET_MATCHES_BY_DIVISION.format(event_id, division_id),
        max_attempts=max_attempts,
        min_delay=min_delay,
        delay_increment=delay_increment,
    )

Ok so right now I am a bit lazy but I got some data.

  1. 2 second delay between calls seems to be safe, as RobotEvents let me make 22,000 API calls in 12 hours with a 2 second delay.
  2. Somewhere in between a 1 and 2 second delay might be safe, but I will need to look further into where exactly.
  3. A repeated one second delay returned “too many requests” error after a very short period of time.

Whenever I’ve done something with the API I just make a new request after the last request finishes resolving, with a 10ms delay in between, and do a 10 second pause every request once the x-ratelimit-remaining header gets below ~7. I haven’t ever gotten ratelimited with this method, at least that I can remember.

The limit starts at 100 and resets back to 100 around every minute, which is fast enough for me to download every match of a V5RC season in like 20 minutes (around 1800 requests). I would imagine it might work differently under high traffic or something, so it’s probably best to just check the header every time.

To build on @iseau395’s suggestion, you could dynamically set a delay based on the x-ratelimit-remaining header with a variant of exponential backoff:

last_delay = 10 # in ms, change start value as desired
last_rate_limit_remaining = 100
for request in requests:
    make request
    delay(last_delay)
    if headers['x-ratelimit-remaining'] < last_rate_limit_remaining:
        last_delay = 2 * last_delay
    else:
        last_delay = max(last_delay - 1, 1)
    last_rate_limit_remaining = headers['x-ratelimit-remaining']