> ## Documentation Index
> Fetch the complete documentation index at: https://docs.elasticfunnels.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Queue

> Deferred background script execution with tag-based cancellation.

Backend scripts can schedule other scripts to run in the background after a delay using the `queue` global. Jobs are stored in Redis and processed by a background worker. This is useful for sending follow-up emails, scheduling reminders, or any task that should happen later without blocking the current request.

## `queue.push(scriptCode, payload, opts?)`

Enqueue a backend script for deferred execution.

```javascript theme={null}
// Send an abandon email 1 hour after quiz completion
queue.push('mailgun', {
  type: 'abandon',
  email: 'user@example.com',
  quizProfile: quizProfile,
  visitorId: visitorId,
}, { delay: 3600, tag: 'abandon:' + visitorId });
```

| Parameter    | Type   | Description                                           |
| ------------ | ------ | ----------------------------------------------------- |
| `scriptCode` | string | The backend script code to execute (e.g. `'mailgun'`) |
| `payload`    | object | Data passed to the script's exported function         |
| `opts`       | object | Optional configuration (see below)                    |

### Options

| Key     | Type   | Default     | Description                                                                                    |
| ------- | ------ | ----------- | ---------------------------------------------------------------------------------------------- |
| `fn`    | string | `'default'` | Name of the exported function to call                                                          |
| `delay` | number | `0`         | Seconds to wait before executing. Minimum **60s** when non-zero, maximum **7 days** (604,800s) |
| `tag`   | string | —           | Logical group for cancellation (max 200 chars)                                                 |

**Returns:** `{ ok: true, jobId: '...' }` on success, or `{ ok: false, error: '...' }` on failure.

### How the target script is called

The queued script's exported function receives the `payload` object as its only argument:

```javascript theme={null}
// scripts/mailgun.js
function handleQueuedEmail(data) {
  if (data.type === 'abandon') {
    sendAbandonEmail(data.email, data.quizProfile, data.visitorId);
  } else {
    sendResultsEmail(data.email, data.quizProfile);
  }
}
export default handleQueuedEmail;
```

If you specify `opts.fn`, a named export is called instead of the default export:

```javascript theme={null}
queue.push('my-script', { userId: 123 }, { fn: 'processUser', delay: 60 });
// → calls my-script.processUser({ userId: 123 }) after 60 seconds
```

## `queue.cancel(tag)`

Cancel all pending jobs with the given tag for the current brand.

```javascript theme={null}
var result = queue.cancel('abandon:' + visitorId);
console.log('Cancelled', result.cancelled, 'jobs');
```

| Parameter | Type   | Description       |
| --------- | ------ | ----------------- |
| `tag`     | string | The tag to cancel |

**Returns:** `{ ok: true, cancelled: N }` where N is the number of jobs removed.

## Example: Multi-step abandon email sequence

Queue 3–4 emails spaced over a few days. Cancel the whole sequence on purchase using the shared tag prefix.

```javascript theme={null}
// On email capture — queue the abandon sequence
var tag = 'abandon:' + visitorId;

queue.push('mailgun', { type: 'abandon_1', email: leadEmail, quizProfile: quizProfile, visitorId: visitorId },
  { delay: 3600,  tag: tag }); // 1 hour

queue.push('mailgun', { type: 'abandon_2', email: leadEmail, quizProfile: quizProfile, visitorId: visitorId },
  { delay: 86400, tag: tag }); // 24 hours

queue.push('mailgun', { type: 'abandon_3', email: leadEmail, quizProfile: quizProfile, visitorId: visitorId },
  { delay: 172800, tag: tag }); // 48 hours

queue.push('mailgun', { type: 'abandon_4', email: leadEmail, quizProfile: quizProfile, visitorId: visitorId },
  { delay: 259200, tag: tag }); // 72 hours

// On purchase — cancel all pending emails in one call
queue.cancel(tag);
```

<Note>
  **Limits per brand:**

  * **25,000 pending jobs** maximum per brand
  * **64 KB** maximum payload size
  * **7-day** maximum delay (604,800 seconds)
  * **60-second** minimum delay when a non-zero delay is set
  * **5 pushes** per script execution
  * **5 cancel calls** per script execution
  * **3 retries** with exponential backoff on failure
  * Jobs expire after **8 days** if not processed
</Note>

<Warning>
  Queued scripts run in a background worker **without session or customer context**. They have access to `cache`, `queue`, and CRM functions, but **not** `request`, `session`, `redirect`, or `response`. Design your scripts to receive all needed data in the `payload`.
</Warning>
