trigger.dev icon indicating copy to clipboard operation
trigger.dev copied to clipboard

Introduce max concurrency to DynamicFlushScheduler

Open mpxr opened this issue 10 months ago • 2 comments

Closes https://github.com/triggerdotdev/trigger.dev/issues/1789

✅ Checklist

  • [x] I have followed every step in the contributing guide
  • [x] The PR title follows the convention.
  • [x] I ran and tested the code works

Testing

  • Added tests to the DynamicFlushScheduler
  • Manual testing by running tasks locally

Changelog

  • Added the maxConcurrency setting to the DynamicFlushScheduler, limiting the number of concurrent requests made to the callback.
  • When the flush queue contains more than batchSize items, invoke the callback with only batchSize events.
  • Added tests for the DynamicFlushScheduler

TODOs:

  • Consider using Array.concat when adding items to currentBatch in addToBatch, as the spread operator is not performant when adding a large number of items.
  • Report pLimit.activeCount, pLimit.pendingCount, and pLimit.concurrency to /metrics.
  • Add a test case to validate both batchSize and flushInterval in a single test.

mpxr avatar Mar 13 '25 17:03 mpxr

⚠️ No Changeset found

Latest commit: 4153e38143c5e9bd96aaeef78426e3c86353a1c6

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

changeset-bot[bot] avatar Mar 13 '25 17:03 changeset-bot[bot]

Walkthrough

This update enhances the DynamicFlushScheduler by introducing concurrency control and improved error handling. An optional maxConcurrency property and the pLimit library are integrated to manage concurrent flush operations. Key methods such as addToBatch, checkAndFlush, and flushNextBatch have been updated to be asynchronous, and new shutdown handling logic has been added to ensure pending batches are processed on termination. Additionally, dependency updates in package.json and new tests for batch processing and signal handling have been incorporated.

Changes

File(s) Summary of Changes
apps/webapp/app/v3/dynamicFlushScheduler.server.ts - Added optional maxConcurrency to config and new properties (MAX_CONCURRENCY, concurrencyLimiter using pLimit)
- Converted addToBatch, checkAndFlush, and flushNextBatch to asynchronous methods
- Introduced shutdown handling with setupShutdownHandlers, shutdown, and timer management methods (clearTimer, resetFlushTimer)
apps/webapp/package.json - Updated dependencies: restored @depot/sdk-node, @internal/run-engine, @internal/zod-worker, and @opentelemetry/api-logs
- Added new dependency p-limit
apps/webapp/test/dynamicFlushScheduler.test.ts - New test file added using Vitest
- Covers scenarios for batch processing, flush intervals, and handling of the SIGTERM signal to ensure graceful shutdown

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Scheduler
    participant Limiter as pLimit
    User->>Scheduler: addToBatch(items)
    Scheduler->>Scheduler: Check batch threshold
    alt Batch threshold reached
        Scheduler->>Scheduler: flushNextBatch()
        Scheduler->>Limiter: Execute flush for sub-batch
        Limiter-->>Scheduler: Return flush result/error
    end
    Scheduler-->>User: Flush complete
sequenceDiagram
    participant OS
    participant Scheduler
    OS->>Scheduler: SIGTERM Received
    Scheduler->>Scheduler: setupShutdownHandlers()
    Scheduler->>Scheduler: shutdown()
    Scheduler->>Limiter: Process remaining batches
    Scheduler-->>OS: Graceful shutdown complete

Possibly related PRs

  • triggerdotdev/trigger.dev#1678: Modifications to DynamicFlushSchedulerConfig and callback function align closely with the scheduler updates.
  • triggerdotdev/trigger.dev#1766: Introduces concurrency management using a similar pLimit mechanism and a maxConcurrentRuns property, indicating a shared focus on controlling concurrency.

Poem

I'm a rabbit dancing in code delight,
Hopping through batches both day and night.
With pLimit guiding each flush in line,
Each async step works oh-so-fine.
Shutdowns are graceful, no need to fear –
A bunny cheers for changes made so clear!
🐇✨

[!WARNING] There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

Scope: all 2 workspace projects  ERR_PNPM_OPTIONAL_DEPS_REQUIRE_PROD_DEPS  Optional dependencies cannot be installed without production dependencies

[!TIP]

⚡🧪 Multi-step agentic review comment chat (experimental)
  • We're introducing multi-step agentic chat in review comments. This experimental feature enhances review discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments. - To enable this feature, set early_access to true under in the settings.
✨ Finishing Touches
  • [ ] 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
  • @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.

coderabbitai[bot] avatar Mar 13 '25 17:03 coderabbitai[bot]