Skip to content

Support debounce with max delay: new jobKeyMode to push run_at forward with an upper bound #583

Open

Description

@IlyaSemenov

Feature description

Add a new jobKeyMode that combines debounce with a maximum delay — i.e., each new call pushes run_at forward (like replace), but never beyond a configurable upper bound relative to when the job was first created.

Proposed API:

addJob(payload, {
  jobKey: "my-key",
  runAt: addSeconds(new Date(), 2),   // debounce window
  jobKeyMode: "debounce",
  maxDebounceSeconds: 10,             // upper bound since first creation
});

Behavior:

Event run_at Notes
T+0s — first call T+2s Job created, created_at = T+0s
T+1s — second call T+3s run_at pushed forward (debounce), still ≤ created_at + 10s
T+3s — third call T+5s Debounce continues
T+9s — fourth call T+10s Would be T+11s, but clamped to T+10s
T+10s — Job executes. Next call starts a fresh cycle

Implementation idea:

The existing _private_jobs table already has a created_at column that is set once when the job row is inserted and is not updated by subsequent addJob calls with the same jobKey. This is exactly the "first enqueued at" timestamp needed for clamping.

When jobKeyMode = "debounce": update run_at to the new value (like replace), but clamp it:

run_at = LEAST(new_run_at, created_at + (maxDebounceSeconds || ' seconds')::interval)

No schema changes required — the feature can be implemented purely as logic in the add_job function.

Alternative API shapes (open to discussion):

// Option A: explicit new mode
jobKeyMode: "debounce",
maxDebounceSeconds: 10,

// Option B: extend preserve_run_at with a tolerance
jobKeyMode: "preserve_run_at",
maxRunAtDrift: 10,

// Option C: generic clamp on replace
jobKeyMode: "replace",
maxDelaySeconds: 10,

No strong preference — whatever fits the library's design philosophy best.

Motivating example

Debounce-with-max-delay is an extremely common pattern in event-driven systems. A concrete case: recalculating derived data after user edits.

// Users vote for ideas in rapid succession — we want to debounce
// the expensive recalculation, but not starve it indefinitely.
addJob("rubrics.recalculateRating", { rubricId }, {
  jobKey: `rubrics.recalculateIdeasRating:${rubricId}`,
  runAt: addSeconds(new Date(), 2),
  jobKeyMode: "preserve_run_at", // compromise: throttle, not debounce
});

The current options force a choice between two extremes:

  • replace — true debounce, but if events arrive every second, the job is postponed forever.
  • preserve_run_at — guaranteed execution at the original time, but ignores recency entirely (throttle, not debounce).

Neither captures the desired semantics: "wait for a pause in activity, but guarantee execution within N seconds."

Other use cases where this applies: webhook coalescing, search index rebuilding, cache invalidation batching, notification grouping, analytics aggregation after user activity bursts.

Breaking changes

None. The existing created_at column on _private_jobs already provides the necessary "first enqueued" anchor. The feature can be implemented as a new jobKeyMode value ("debounce") with an additive option (maxDebounceSeconds), requiring no schema migration and no changes to existing modes.

Supporting development

I [tick all that apply]:

  • am interested in building this feature myself
  • am interested in collaborating on building this feature
  • am willing to help testing this feature before it's released
  • am willing to write a test-driven test suite for this feature (before it exists)
  • am a Graphile sponsor ❤️
  • have an active support or consultancy contract with Graphile

Activity

  1. added
    enhancement
    on Sep 8, 2026
  2. Krrishkumar125 commented on Oct 22, 2026

    @Krrishkumar125

    Hi @benjie, I'd like to work on this and wanted to agree the design before writing any code.

    I read through add_job in the current schema. Here's what I'd propose:

    API: Option A from the issue, a new jobKeyMode: "debounce" plus a maxDebounceSeconds option (alternative name: maxDelay). It behaves exactly like replace except for how run_at is computed on conflict:

    run_at = (case
      when job_key_mode = 'debounce' and jobs.attempts = 0
        then least(excluded.run_at, jobs.created_at + make_interval(secs => max_debounce_seconds))
      when job_key_mode = 'preserve_run_at' and jobs.attempts = 0 then jobs.run_at
      else excluded.run_at
    end)

    On insert it's just run_at, like today, so the first call starts the window.

    Things I noticed / edge cases:

    1. There's no table change, but add_job would get a new parameter, so it still needs a migration that replaces the function (and add_jobs, which currently takes job_key_preserve_run_at boolean, would need an equivalent so batch adds stay consistent).
    2. created_at is never updated on conflict, which is what makes the clamp work. But if the existing row has already failed and is waiting to retry (attempts > 0), its created_at can be very old. My suggestion is to only clamp while attempts = 0, mirroring preserve_run_at, and otherwise fall back to replace behaviour.
    3. Locked (running) jobs: same as replace. The key gets detached and a new job is inserted, which starts a fresh window. That matches "next call starts a fresh cycle" from the issue.
    4. debounce without maxDebounceSeconds: I'd make that an error (it's just replace), rather than silently behaving like replace.
    5. If runAt is already past the clamp on the first call, should the job run at runAt, or at created_at + max? I'd keep it simple and only clamp on conflict.

    Tests I'd add: the timeline from the issue (pushed forward, then clamped), the retrying-job case, the locked-job case, the missing-option error, and add_jobs batch parity.

    Questions for you:

    • Does a new mode fit, or would you rather this be an option on replace (Option C)?
    • Are you OK with the migration for the new add_job/add_jobs parameter, or is there a preferred way to pass extra job-key options?

    Happy to adjust before I start on a PR.

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

    enhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions