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

Improve threading when calling the accessy api. #585

Merged
merged 1 commit into from
Dec 26, 2024

Conversation

HalfVoxel
Copy link
Contributor

@HalfVoxel HalfVoxel commented Dec 16, 2024

The previous code started one thread per member, which is way too much, and just resulted
in a ton of rate limit errors.

Summary by CodeRabbit

  • New Features

    • Enhanced request handling logic for improved performance during high traffic.
    • Optimized threading model for user data retrieval, allowing for more efficient processing of user IDs.
  • Bug Fixes

    • Adjusted backoff strategy for handling HTTP 429 responses to improve retry behavior.

@HalfVoxel HalfVoxel requested a review from emanuelen5 December 16, 2024 20:32
Copy link
Contributor

coderabbitai bot commented Dec 16, 2024

Walkthrough

The pull request introduces modifications to the accessy.py file, focusing on improving request handling and threading efficiency. The changes involve adjusting the backoff strategy for HTTP 429 responses in the request function and refactoring the threading implementation in the _user_ids_to_accessy_members method. The updates aim to optimize request retries and concurrent user data retrieval by reducing the number of threads and managing them more effectively.

Changes

File Change Summary
api/src/multiaccessy/accessy.py - Modified request function's backoff strategy for HTTP 429 responses
- Reduced initial backoff time from 1.0 to 0.3 seconds
- Changed backoff multiplier to a fixed 1.5x
- Refactored threading in _user_ids_to_accessy_members method
- Implemented chunk-based thread processing
- Added time module import

Sequence Diagram

sequenceDiagram
    participant Client
    participant AccessyAPI
    participant ThreadPool
    
    Client->>ThreadPool: Divide user IDs into chunks
    loop Process Chunks
        ThreadPool->>AccessyAPI: Fetch user details
        AccessyAPI-->>ThreadPool: Return user membership
    end
    ThreadPool-->>Client: Consolidated user data
Loading

Poem

🐰 Threads dancing, requests light,

Backoff strategy now takes flight,

Chunks of users, swift and neat,

API calls now more discreet,

Efficiency hops with rabbit might! 🚀


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 33e5c40 and 533c111.

📒 Files selected for processing (1)
  • api/src/multiaccessy/accessy.py (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • api/src/multiaccessy/accessy.py

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (2)
api/src/multiaccessy/accessy.py (2)

60-68: LGTM! Backoff strategy improvements look good.

The changes to the backoff strategy are well thought out:

  • Lower initial backoff allows for quicker retry attempts
  • Fixed multiplier provides predictable exponential backoff
  • Random factor helps prevent thundering herd problem

Fix typo in warning message

There's a typo in "reqeusts" in the warning message.

-                f"requesting accessy returned 429, too many reqeusts, try {i+1}/{max_tries}, retrying in {backoff}s, {path=}"
+                f"requesting accessy returned 429, too many requests, try {i+1}/{max_tries}, retrying in {backoff}s, {path=}"

545-561: LGTM! Threading model improvements significantly reduce thread count.

The new implementation effectively addresses the rate limiting issues by:

  • Limiting maximum thread count to 4
  • Chunking user IDs across threads
  • Using round-robin distribution for balanced load

Consider these enhancements to the threading implementation

  1. Make the thread count configurable via environment variable
  2. Add error handling in the worker function
  3. Consider using ThreadPoolExecutor for better thread management
+MAX_THREADS = int(config.get("ACCESSY_MAX_THREADS", default="4"))
+
 def _user_ids_to_accessy_members(self, user_ids: Iterable[UUID]) -> list[AccessyMember]:
     threads = []
     user_ids = list(user_ids)
-    thread_count = min(4, len(user_ids))
+    thread_count = min(MAX_THREADS, len(user_ids))
     accessy_members = []

     for i in range(thread_count):
         slice = user_ids[i::thread_count]
         member_slice = [AccessyMember(user_id=uid) for uid in slice]
         accessy_members.extend(member_slice)

         def worker(member_slice: list[AccessyMember]) -> None:
-            for member in member_slice:
-                fill_user_details(member)
-                fill_membership_id(member)
+            try:
+                for member in member_slice:
+                    fill_user_details(member)
+                    fill_membership_id(member)
+            except Exception as e:
+                logger.error(f"Error processing members: {e}")
+                raise

         t = threading.Thread(target=worker, args=(member_slice,))
         threads.append(t)
         t.start()

Alternative implementation using ThreadPoolExecutor:

from concurrent.futures import ThreadPoolExecutor, as_completed

def _user_ids_to_accessy_members(self, user_ids: Iterable[UUID]) -> list[AccessyMember]:
    user_ids = list(user_ids)
    thread_count = min(MAX_THREADS, len(user_ids))
    accessy_members = []

    def process_chunk(chunk: list[UUID]) -> list[AccessyMember]:
        members = [AccessyMember(user_id=uid) for uid in chunk]
        for member in members:
            fill_user_details(member)
            fill_membership_id(member)
        return members

    # Split user_ids into chunks
    chunks = [user_ids[i::thread_count] for i in range(thread_count)]
    
    with ThreadPoolExecutor(max_workers=thread_count) as executor:
        futures = [executor.submit(process_chunk, chunk) for chunk in chunks]
        for future in as_completed(futures):
            try:
                chunk_members = future.result()
                accessy_members.extend(chunk_members)
            except Exception as e:
                logger.error(f"Error processing members: {e}")
                raise

    # Filter out API keys
    accessy_members = [m for m in accessy_members if m.phone is not APPLICATION_PHONE_NUMBER]
    return accessy_members
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 34cb801 and 33e5c40.

📒 Files selected for processing (1)
  • api/src/multiaccessy/accessy.py (3 hunks)

@HalfVoxel HalfVoxel force-pushed the aron/accessy_threading branch from 33e5c40 to 2729ca1 Compare December 16, 2024 21:00
Copy link
Member

@emanuelen5 emanuelen5 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM. Not sure how the backoff affects it, but if it works, it works.

@emanuelen5
Copy link
Member

I fixed the build so you can now rebase on main to get the tests running.

@@ -541,14 +542,23 @@ def fill_membership_id(user: AccessyMember) -> None:
user.membership_id = data["id"]

threads = []
user_ids = list(user_ids)
thread_count = min(4, len(user_ids))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't follow this completely. Doesn't this still create one thread per user_id as before?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, it creates at most 4 threads.

The previous code started one thread per member, which is way too much, and just resulted
in a ton of rate limit errors.
@HalfVoxel HalfVoxel force-pushed the aron/accessy_threading branch from 2729ca1 to 533c111 Compare December 26, 2024 11:09
@HalfVoxel HalfVoxel merged commit fbb4ca5 into main Dec 26, 2024
10 of 11 checks passed
@HalfVoxel HalfVoxel deleted the aron/accessy_threading branch December 26, 2024 11:13
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.

3 participants