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

feat(search-indexer): Wait before doing another request to Elasticsearch in case of 429 status code #16215

Merged
merged 6 commits into from
Sep 30, 2024

Conversation

RunarVestmann
Copy link
Member

@RunarVestmann RunarVestmann commented Sep 30, 2024

Wait before doing another request to Elasticsearch in case of 429 status code

Why

  • Calling Elasticsearch too often causes it to return a "Too many requests" status code, we'd like to wait and try again in those cases

Checklist:

  • I have performed a self-review of my own code
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • Formatting passes locally with my changes
  • I have rebased against main before asking for a review

Summary by CodeRabbit

  • Bug Fixes
    • Improved error handling and retry logic for ElasticSearch service requests, enhancing resilience against rate limits.
    • Enhanced response management for fetching entries, particularly in pagination and total hit counts.
  • New Features
    • Introduced a retry mechanism for handling ElasticSearch service responses with 429 status codes, allowing for better request management.
    • Enhanced bulk request handling in the ElasticSearch service, including improved logging and error management.

@RunarVestmann RunarVestmann added the automerge Merge this PR as soon as all checks pass label Sep 30, 2024
@RunarVestmann RunarVestmann requested review from a team as code owners September 30, 2024 14:52
Copy link
Contributor

coderabbitai bot commented Sep 30, 2024

Walkthrough

The changes in the ContentfulService and ElasticService classes enhance error handling and introduce retry mechanisms for handling 429 status codes from the ElasticSearch service. The resolveNestedEntries method in ContentfulService allows for up to three retries with increasing delays, while the bulkRequest method in ElasticService implements similar retry logic. Additionally, constants for configuration have been introduced, and the overall structure of the methods has been improved for clarity and maintainability.

Changes

File Path Change Summary
libs/cms/src/lib/search/contentful.service.ts Enhanced resolveNestedEntries method with retry logic for 429 status codes; no signature changes.
libs/content-search-toolkit/src/services/elastic.service.ts Improved bulkRequest method with retry logic for 429 status codes and adjusted chunk size; added constants for configuration.

Possibly related PRs

Suggested labels

automerge

Suggested reviewers

  • mannipje

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 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.

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

🧹 Outside diff range and nitpick comments (2)
libs/cms/src/lib/search/contentful.service.ts (2)

486-488: LGTM: Retry mechanism implemented for handling 429 errors.

The implementation of a retry mechanism with exponential backoff for handling 429 (Too Many Requests) errors from Elasticsearch is a good approach. This aligns well with the PR objective and helps prevent overwhelming the Elasticsearch service.

Consider extracting delay and retry values to configurable constants.

For better flexibility across different environments, consider extracting the initial delay (500ms) and the number of retries (3) to configurable constants. This would allow easier adjustment of these values without modifying the code.

Here's a suggested implementation:

const INITIAL_RETRY_DELAY_MS = 500;
const MAX_RETRY_ATTEMPTS = 3;

// In the method:
let delay = INITIAL_RETRY_DELAY_MS;
let retries = MAX_RETRY_ATTEMPTS;

525-533: Add logging for retry attempts.

To improve observability and aid in debugging, consider adding log statements for each retry attempt. This will help track the frequency and duration of retries in production.

Here's a suggested implementation:

if (error?.statusCode === 429 && retries > 0) {
  logger.warn(`Received 429 error. Retrying in ${delay}ms. Attempts left: ${retries}`);
  await new Promise((resolve) => {
    setTimeout(resolve, delay)
  })
  retries -= 1;
  delay *= 2;
  continue;
}
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between efbef76 and 85d744f.

📒 Files selected for processing (1)
  • libs/cms/src/lib/search/contentful.service.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
libs/cms/src/lib/search/contentful.service.ts (1)

Pattern libs/**/*: "Confirm that the code adheres to the following:

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
🔇 Additional comments (2)
libs/cms/src/lib/search/contentful.service.ts (2)

486-536: Summary: Effective implementation with room for minor improvements

The changes successfully implement a retry mechanism for handling 429 errors from Elasticsearch, addressing the main objective of the PR. The use of exponential backoff is a good practice. Consider the following improvements:

  1. Extract retry-related values to configurable constants for better flexibility.
  2. Add logging for retry attempts to improve observability.
  3. Verify the impact of the retry mechanism on overall system performance, especially during high load scenarios.

These minor enhancements will further improve the robustness and maintainability of the implementation.


486-536: Verify the impact of retry mechanism on system performance.

While the retry mechanism is a good addition, it's important to verify its impact on the overall system performance, especially during high load scenarios.

Run the following script to check for any performance-related logs or metrics:

This will help identify if there are any existing performance monitoring mechanisms in place and if additional instrumentation is needed for the new retry logic.

✅ Verification successful

Performance Monitoring Verified

Existing performance monitoring mechanisms are in place, utilizing metrics and monitoring tools to track system performance. The current setup should adequately capture the impact of the retry mechanism on system performance during high load scenarios.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for performance-related logs or metrics

# Test: Search for performance-related logs
rg --type typescript "performance|latency|duration"

# Test: Check for any existing metrics collection
rg --type typescript "metrics|monitoring"

Length of output: 167


Script:

#!/bin/bash
# Description: Check for performance-related logs or metrics

# Test: Search for performance-related logs in TypeScript files
rg --glob '*.ts' --glob '*.tsx' "performance|latency|duration"

# Test: Check for any existing metrics collection in TypeScript files
rg --glob '*.ts' --glob '*.tsx' "metrics|monitoring"

Length of output: 58260

@RunarVestmann RunarVestmann removed the automerge Merge this PR as soon as all checks pass label Sep 30, 2024
Copy link

codecov bot commented Sep 30, 2024

Codecov Report

Attention: Patch coverage is 9.75610% with 37 lines in your changes missing coverage. Please review.

Project coverage is 36.77%. Comparing base (95b39ac) to head (2ffb507).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
...ent-search-toolkit/src/services/elastic.service.ts 8.69% 21 Missing ⚠️
libs/cms/src/lib/search/contentful.service.ts 11.11% 16 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main   #16215      +/-   ##
==========================================
- Coverage   36.77%   36.77%   -0.01%     
==========================================
  Files        6784     6785       +1     
  Lines      139840   139849       +9     
  Branches    39764    39741      -23     
==========================================
  Hits        51431    51431              
- Misses      88409    88418       +9     
Flag Coverage Δ
api 3.39% <ø> (ø)
api-domains-auth-admin 48.77% <ø> (ø)
api-domains-communications 39.92% <9.75%> (-0.10%) ⬇️
application-system-api 41.62% <9.75%> (-0.03%) ⬇️
application-template-api-modules 23.74% <ø> (+<0.01%) ⬆️
application-ui-shell 21.29% <ø> (ø)
cms 0.43% <0.00%> (-0.01%) ⬇️
cms-translations 39.05% <9.75%> (-0.10%) ⬇️
content-search-toolkit 8.16% <0.00%> (-0.34%) ⬇️
judicial-system-api 18.30% <ø> (-0.17%) ⬇️
judicial-system-backend 55.30% <9.75%> (-0.08%) ⬇️
services-user-notification 47.07% <9.75%> (-0.10%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
libs/cms/src/lib/search/contentful.service.ts 7.01% <11.11%> (+0.41%) ⬆️
...ent-search-toolkit/src/services/elastic.service.ts 13.25% <8.69%> (-0.09%) ⬇️

... and 9 files with indirect coverage changes


Continue to review full report in Codecov by Sentry.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 95b39ac...2ffb507. Read the comment docs.

@datadog-island-is
Copy link

datadog-island-is bot commented Sep 30, 2024

Datadog Report

All test runs ced1fa0 🔗

12 Total Test Services: 0 Failed, 11 Passed
🔻 Test Sessions change in coverage: 5 decreased, 24 no change

Test Services
This report shows up to 10 services
Service Name Failed Known Flaky New Flaky Passed Skipped Total Time Code Coverage Change Test Service View
api 0 0 0 4 0 2.72s 1 no change Link
api-domains-auth-admin 0 0 0 18 0 13.34s 1 no change Link
api-domains-communications 0 0 0 5 0 31.64s 1 decreased (-0.15%) Link
api-domains-license-service 0 0 0 0 0 552ms 1 no change Link
application-system-api 0 0 0 111 2 3m 41.86s 1 no change Link
application-template-api-modules 0 0 0 109 0 1m 49.84s 1 no change Link
cms-translations 0 0 0 3 0 28.95s 1 decreased (-0.15%) Link
content-search-toolkit 0 0 0 4 0 11.34s 1 decreased (-0.41%) Link
judicial-system-api 0 0 0 57 0 6.36s 1 no change Link
judicial-system-backend 0 0 0 20947 0 20m 44.08s 1 decreased (-0.09%) Link

🔻 Code Coverage Decreases vs Default Branch (5)

  • content-search-toolkit - jest 8.35% (-0.41%) - Details
  • api-domains-communications - jest 49.13% (-0.15%) - Details
  • cms-translations - jest 48.56% (-0.15%) - Details
  • judicial-system-backend - jest 58.16% (-0.09%) - Details
  • services-user-notification - jest 69.77% (-0.08%) - Details

@RunarVestmann RunarVestmann added the automerge Merge this PR as soon as all checks pass label Sep 30, 2024
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: 4

🧹 Outside diff range and nitpick comments (1)
libs/content-search-toolkit/src/services/elastic.service.ts (1)

117-159: Add unit tests for the new retry mechanism

To ensure the reliability of the retry logic in bulkRequest, consider adding unit tests that simulate different scenarios, such as successful retries after a 429 error and failures after exceeding the maximum retry count.

Would you like assistance in writing these unit tests or opening a GitHub issue to track this task?

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between b5592de and 8d69027.

📒 Files selected for processing (2)
  • libs/cms/src/lib/search/contentful.service.ts (2 hunks)
  • libs/content-search-toolkit/src/services/elastic.service.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • libs/cms/src/lib/search/contentful.service.ts
🧰 Additional context used
📓 Path-based instructions (1)
libs/content-search-toolkit/src/services/elastic.service.ts (1)

Pattern libs/**/*: "Confirm that the code adheres to the following:

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."

@oddsson oddsson added automerge Merge this PR as soon as all checks pass and removed automerge Merge this PR as soon as all checks pass labels Sep 30, 2024
@kodiakhq kodiakhq bot merged commit ff7d751 into main Sep 30, 2024
58 checks passed
@kodiakhq kodiakhq bot deleted the feat/search-indexer-backoff-when-too-many-requests branch September 30, 2024 23:25
thoreyjona pushed a commit that referenced this pull request Oct 2, 2024
…rch in case of 429 status code (#16215)

* Wait in case of 429 status code from ES

* Add constants

* Add retry logic to ES calls

---------

Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
automerge Merge this PR as soon as all checks pass
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants