Skip to content

Fix unhandled promise rejections and optimize array iterations in cron jobs #303

Closed

Description

@aadityakumarsah

The tickCronJobs and startCronJobs functions in packages/modelence/src/cron/jobs.ts currently use standard Array.prototype.forEach to loop through cron job records and objects.

In tickCronJobs, this is problematic because it uses an async callback inside a synchronous forEach loop. The forEach loop does not wait for the promises to resolve, meaning the asynchronous execution of runCronJob runs detached from the tick cycle. This can potentially lead to unhandled promise rejections crashing the Node.js process and creates a race condition if multiple intervals tick before the previous jobs finish safely.

Additionally, using forEach across the file introduces minor but unnecessary closure allocation overhead in a fast-running interval.

Proposed Solution:

  • Refactor the forEach(async (job) => { ... }) loop in tickCronJobs to use await Promise.all(Object.values(cronJobs).map(async (job) => { ... })). This allows concurrent execution of the jobs while properly awaiting all of them before the tick cycle completes.
  • Replace synchronous forEach loops over arrays and object values in startCronJobs with optimized for...of loops to reduce closure allocations and improve readability.

Activity

  1. omegascorp commented on Aug 10, 2026

    @omegascorp
    Collaborator

    Thanks for looking at this. Closing — runCronJob already wraps await handler() in a try/catch, so the forEach(async ...) here can't produce the rejection described.

    You were close to a real one, though: cronJobsCollection.upsertOne runs before that try block, so a failed write leaves state.isRunning stuck at true, and the job gets skipped until the timeout clears it. Tracking in #338.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions