Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update AsyncClient to use Semaphores #1916

Open
wants to merge 3 commits into
base: master
Choose a base branch
from

Conversation

supRy
Copy link

@supRy supRy commented Jun 18, 2022

Problem: All requests in tweepy first try to make the request and if there is a rate limit in affect, then they choose to sleep until the rate limit is expired. In other words, they operate with no memory. This is fine in synchronous code, only a max of one request would be sleeping at once. However, in the AsyncClient, a user could send 1,000 requests within a second. The first ones would work, until the rate limit was met, then the rest would then start to sleep simultaneously. Which means they will all get released simultaneously.

What this leads to is a bunch of extra requests to Twitter that all return 429.

This pull requests implements a custom Semaphore that acts as a memory of the current rate limit and doesn't send more responses to Twitter than what is known can be supported. The Semaphore automatically resets at the reset time and releases more requests to Twitter.

Since different endpoints have different rate limits, the semaphores are stored in a defaultdict so a new semaphore is automatically created for each endpoint the user is requesting. It is understood that some endpoints share a rate limit. This was mostly ignored, but each response that is returned updates the semaphore, so if another request had dropped the value on another endpoint the semaphore eventually gets updated (I think).

I'm not set up to test tweepy (I don't have a twitter developer account), so if someone else can do some integration testing, that would be good. I did some tests in a mocked up scenario, but need to actually integrate with the Twitter API to make sure it works before this gets pulled.

Thanks for your consideration!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

1 participant