Skip to main content

Overview

A logic function run is capped by its timeoutSeconds (900 seconds maximum). Anything that can’t finish in that window — a full re-sync, a per-record fan-out, a third-party API that rate-limits you — has to be split into smaller runs. enqueueJobs does exactly that: it asks the Twenty workers to run one of your app’s logic functions later, once per payload, each run in its own process with its own timeout budget. The caller returns immediately.

Enqueue runs

Import enqueueJobs from twenty-sdk/logic-function, point it at the universalIdentifier of the logic function to run, and pass one payload per run to enqueue.
src/logic-functions/sync-all-contacts.ts
Each run receives its payload as the handler argument, exactly like any other trigger. The target must belong to the same application as the caller — enqueuing another app’s function is rejected with Logic function not found and nothing is enqueued. A single call accepts up to 200 jobs.
enqueueJobs returns as soon as the jobs are accepted, not when they have run. It does not return the targets’ results — have each target write what it produces to the key-value store or to a workspace record if you need to read it back. To find out whether a run finished, poll its job status.
The older enqueueJob helper, which enqueues a single job per call, is deprecated. Use enqueueJobs with a one-element jobs list instead. The payloads argument is deprecated too — pass jobs instead, which takes the same payload per run and lets you name each one. The jobIds field of the result is deprecated as well: read each id from jobs instead.

Poll jobs

enqueueJobs returns one entry per enqueued run in jobs, each with its jobId, in the same order as the jobs you passed. getJobs reads back where those runs got to, in one call.
A single getJobs call reads at most 200 ids, the same ceiling enqueueJobs applies to a batch. Each entry carries the id you asked for: A job that has not been picked up yet normally reads as PRIORITIZED rather than WAITING, because application jobs are queued at a fixed low priority. COMPLETED and FAILED are the terminal states. A poll loop should also give up on its own after a bounded number of attempts rather than waiting forever, since a run is only readable for as long as the queue retains it: 4 hours after completing, 7 days after failing, and in both cases only the most recent 1000 jobs in that state. getJobs returns only the jobs it still holds, so an id that has been evicted — or never existed — is simply absent from the result rather than erroring the whole batch. Compare what you get back against what you asked for to spot those, and treat a missing id as “no longer known”, which is not the same answer as “it never ran”. Statuses are scoped to the workspace the call is made from, so one workspace can never read another workspace’s job.

Choose your own job id

Pass jobs instead of payloads to name each run yourself. The id you pass is the one getJobs takes, so a caller can poll a job without having to store what enqueueJobs returned.
An id is at most 128 characters of letters, digits, _, . or -, and no two jobs in one call may share one. Pass either payloads or jobs, never both. When you omit jobId, Twenty generates one. A jobId is also an idempotency key: enqueuing an id that the queue still holds is accepted but does not start a second run, and getJobs keeps reporting the first one. This makes a retried enqueue safe. Two caveats: the guarantee only lasts as long as the job is retained, so the same id can start a fresh run once the original has been evicted, and ids are shared by every app in a workspace, so prefix yours if a collision would matter.

Job options

Options apply to every run in the batch.
To set the retry limit once for every queued run of a function, declare retryLimit on the function itself. It applies to runs started by enqueueJobs, cron, database events and server routes, and a retryLimit passed to enqueueJobs overrides it for that call. Without it, the defaults are 0 for enqueueJobs, 10 for cron and 3 for database events and server routes.

Pace runs with a limiter

Pass limiter: { max, durationMs } to space the runs of a call one interval of durationMs / max apart, for example to stay under a third-party rate limit.
Here a run becomes eligible every 6 seconds. How it works:
  • Calls for the same function in the same workspace with the same max and durationMs share one schedule, so a second call continues after the runs the first one reserved. Changing either value starts a separate schedule.
  • Each run is given the next free slot, or now if the schedule is idle, and the next slot moves one interval later. Runs are spaced evenly, never in bursts.
  • There is no horizon: a large batch can be scheduled days ahead. The usual queue memory limits still apply, and a long backlog holds its memory until it drains.
  • max and durationMs must be positive integers with an interval between 100 ms and 1 hour. Combining limiter with delayMs, even delayMs: 0, is rejected with INVALID_INPUT and nothing is enqueued.
  • Only the runs of calls that pass limiter are paced. Retries keep their own backoff, and runs started by cron, database events, onConnect or server routes are not paced.
  • Re-enqueuing a jobId the queue still holds does not take another slot.
  • The limiter spaces when runs become eligible. It does not cap how many run at the same time, and a run can start later than its slot when workers are busy.
  • If pacing is unavailable because of a technical failure, the runs are enqueued without pacing rather than refused.

When a job is scheduled

Each entry of jobs returned by enqueueJobs, and each status returned by getJobs, carries scheduledAt: when the job first became eligible to run, in epoch milliseconds. It is set once, when the job is accepted, and never changes afterwards, including across retries. Enqueuing a jobId the queue still holds reports the existing job’s scheduledAt. Once the job has been evicted, a new job with the same id gets a new one. scheduledAt is not a prediction of when the job starts: compare it with startedAt to see how long it waited for a worker.
Priority is not configurable yet. Enqueued jobs always run at the lowest priority, so platform work is never delayed behind application jobs. Control over priority is coming soon.
The queued run inherits the acting user of the function that enqueued it, so it acts with the same permissions.

Queue memory

Queued jobs live in memory until they finish, so each workspace and each application may only hold a share of the queue memory that others leave free. A single job is also capped at 20 MB of serialized payload. enqueueJobs reports what each call used. These fields need Twenty 2.57.0 or later, which is also the minimum server version of the SDK: When a limit is reached, the whole call is refused and nothing is enqueued: Keep payloads small: pass record ids and fetch the records inside the run instead of embedding them. If availableBytes runs low, enqueue fewer jobs at once or chain them with delayMs.

Retry a transient failure

Twenty does not retry every exception from application code. An ordinary thrown error is treated as a permanent failure. For a transient failure, a queued logic function can request up to three retries by throwing RetryableLogicFunctionError.
Throw RetryableLogicFunctionError directly when possible. If you extend it, do not replace its name: Twenty recognizes the serialized name RetryableLogicFunctionError across execution runtimes. retryCount is 0 for the initial execution and increases only when application code requests a retry. maxRetries is at most 3 and can be lower when the queued job has a smaller overall retry limit. Platform failures do not increase retryCount, although they still consume the queue’s overall safety budget. The queue delays retry attempts with exponential backoff and jitter. The exact delay is intentionally not guaranteed, so application code should not depend on a retry happening at a precise time. Once maxRetries is reached, another RetryableLogicFunctionError is recorded as the final application failure without another execution.
Retries re-run the whole handler and may happen after some side effects succeeded. Make the handler idempotent before requesting retries.

React when a job fails for good

A queued run can end without your code reaching its own error handling, for example when it hits timeoutSeconds. Add onJobFailure next to handler, and Twenty calls it once a queued run of the function fails and will not be retried.
src/logic-functions/answer-request.ts
onJobFailure receives the failure as its first argument and the same execution context as handler as its second: It runs as its own queued job, in a fresh process, with the function’s timeoutSeconds. Its job id is the failed job’s id followed by .on-failure, so you can poll it with getJobs, and one failure never starts it twice. It runs after:
  • an error thrown by your code that is not retried, including a RetryableLogicFunctionError once maxRetries is reached;
  • a timeout;
  • a platform error once the queued job has no attempts left;
  • the worker process running the job crashing twice. The queue runs the job again after the first crash, and after the second it fails the job with job stalled more than allowable limit. onJobFailure then runs once a worker picks the job up, so after a full outage it runs when workers are back.
It does not run:
  • for executions that do not go through the job queue, such as tool calls, workflow steps and the resolver of a server route (a target function the resolver queues is covered);
  • when onJobFailure itself fails, so it cannot loop.
The failed run may have completed some side effects before it stopped. Do not re-run the same work blindly from onJobFailure; record the failure or tell the user instead. Make it idempotent, because the queue retries it up to three times on a platform error. Delivery is best effort: if a worker dies in the instant between a job failing and onJobFailure being queued, it does not run.

Use it: page through a long sync

The classic shape is a function that enqueues itself with the next cursor. Each run does one page of work well inside its own timeout, and the chain stops when there is nothing left.
src/logic-functions/sync-contacts-page.ts

Fan out per record

When the work is naturally per-item, enqueue one job per item in a single call and let the workers process them in parallel instead of looping inline.

Good practice for long-running work

Two rules cover almost every long job: recurse instead of looping, and process a bounded chunk per run. A run that tries to do everything is the failure mode — it hits the timeout, and with a retry it starts the whole thing again from zero. Instead, size one chunk so it comfortably finishes inside timeoutSeconds, persist your position, and enqueue the next run.
src/logic-functions/enrich-companies-batch.ts
What makes this hold up:
  • Size the chunk from the slowest item, not the average. CHUNK_SIZE × worst-case item time has to fit in timeoutSeconds with room to spare, or the tail of a chunk is lost when the run is cut off.
  • Make the terminating condition explicit. Recurse only while a full chunk came back. A chain that stops on “no results” alone will keep going forever if the source ever returns a short page mid-way.
  • Persist progress before enqueuing the next run, so a failed link restarts from the last completed chunk instead of the beginning.
  • Keep each chunk idempotent. Reprocessing one chunk after a retry must not double-write — key writes on the record or external id you are processing.
  • Pace a fan-out that hits a rate-limited third party with a limiter, or use a chunked chain with delayMs. Thousands of jobs enqueued without either all become eligible immediately.