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

# Cancel Batch Job

> Cancel a scheduled, pending, or running batch job. Stops new calls and marks remaining contacts as cancelled.

## Overview

Cancels a batch job permanently. Behavior depends on job status:

* **Scheduled**: Cancels Redis scheduled job + updates database
* **Pending/Running**: Marks remaining contacts as cancelled
* **Completed/Failed/Cancelled**: Returns error (cannot cancel)

Running calls complete normally; only pending/queued contacts are cancelled.

## Request

```bash theme={null}
POST /batch/jobs/{batch_job_id}/cancel
```

## Path Parameters

| Parameter      | Type   | Required | Description                 |
| -------------- | ------ | -------- | --------------------------- |
| `batch_job_id` | string | ✅        | Unique batch job identifier |

## Response

```json theme={null}
{
  "success": true,
  "message": "Scheduled job cancelled successfully",
  "batchJobId": "batch_xyz789",
  "redisJobCancelled": true,
  "contactsCancelled": 58
}
```

### Response Fields

| Field               | Type    | Description                               |
| ------------------- | ------- | ----------------------------------------- |
| `success`           | boolean | Whether cancellation succeeded            |
| `message`           | string  | Cancellation result description           |
| `batchJobId`        | string  | Cancelled batch job ID                    |
| `redisJobCancelled` | boolean | Whether Redis scheduled job was cancelled |
| `contactsCancelled` | integer | Number of contacts marked as cancelled    |

## Examples

### Example 1: Cancel Scheduled Job

```bash theme={null}
curl -X POST "https://api.talkifai.com/batch/jobs/batch_xyz789/cancel" \
  -H "Authorization: Bearer YOUR_API_KEY"
```

**Response:**

```json theme={null}
{
  "success": true,
  "message": "Scheduled job cancelled successfully",
  "batchJobId": "batch_xyz789",
  "redisJobCancelled": true,
  "contactsCancelled": 100
}
```

### Example 2: Cancel Running Job

```bash theme={null}
curl -X POST "https://api.talkifai.com/batch/jobs/batch_abc123/cancel" \
  -H "Authorization: Bearer YOUR_API_KEY"
```

**Response:**

```json theme={null}
{
  "success": true,
  "message": "Job was already running - cancelled remaining contacts",
  "batchJobId": "batch_abc123",
  "redisJobCancelled": false,
  "contactsCancelled": 42
}
```

### Example 3: Cancel Already Completed Job (Error)

```bash theme={null}
curl -X POST "https://api.talkifai.com/batch/jobs/batch_completed/cancel" \
  -H "Authorization: Bearer YOUR_API_KEY"
```

**Response:**

```json theme={null}
{
  "detail": "Cannot cancel job in 'completed' status"
}
```

## Behavior by Status

| Job Status  | Cancellation Behavior                                |
| ----------- | ---------------------------------------------------- |
| `scheduled` | Cancels Redis defer job + marks DB as cancelled      |
| `pending`   | Marks all contacts as cancelled                      |
| `running`   | Marks remaining (non-terminal) contacts as cancelled |
| `completed` | ❌ Error: Cannot cancel completed job                 |
| `failed`    | ❌ Error: Cannot cancel failed job                    |
| `cancelled` | ❌ Error: Already cancelled                           |

## Contact Statuses Affected

When cancelling a running job, only contacts in **non-terminal** statuses are cancelled:

**Cancelled Statuses:**

* `pending` — Not yet called
* `queued` — Waiting for retry
* `no_answer` — Will be retried
* `busy` — Will be retried
* `timeout` — Will be retried

**Not Affected (Terminal Statuses):**

* `completed` — Already successful
* `failed` — Final failure
* `blocked` — Permanently blocked
* `invalid_number` — Invalid phone number
* `carrier_error` — Carrier error (final)
* `cancelled` — Already cancelled

## Error Handling

### 404 Not Found

```json theme={null}
{
  "detail": "Batch job not found"
}
```

### 400 Bad Request

```json theme={null}
{
  "detail": "Cannot cancel job in 'completed' status"
}
```

| Error Code         | Cause                                       |
| ------------------ | ------------------------------------------- |
| `job_not_found`    | Batch job ID doesn't exist                  |
| `already_terminal` | Job is in completed/failed/cancelled status |

### 500 Internal Server Error

```json theme={null}
{
  "detail": "Failed to cancel batch job"
}
```

## Use Cases

### Cancel Due to Error in Campaign

If you discover an error in your campaign (wrong message, wrong numbers):

```bash theme={null}
# Immediately cancel the job
curl -X POST "https://api.talkifai.com/batch/jobs/batch_xyz789/cancel" \
  -H "Authorization: Bearer YOUR_API_KEY"
```

### Cancel Scheduled Job Before Start Time

```bash theme={null}
# Job scheduled for 9 AM, but you want to cancel at 8 AM
curl -X POST "https://api.talkifai.com/batch/jobs/batch_scheduled/cancel" \
  -H "Authorization: Bearer YOUR_API_KEY"
```

## Related

* [Create Batch Job](/api-reference/endpoint/create-batch-job) — Create a new batch job
* [Get Batch Job Detail](/api-reference/endpoint/get-batch-job) — Get job status
* [Start Batch Job](/api-reference/endpoint/start-batch-job) — Start scheduled job immediately
* [Reschedule Batch Job](/api-reference/endpoint/reschedule-batch-job) — Change scheduled time
* [Batch Calling Guide](/platform/batch-calling) — Complete guide to batch campaigns


## OpenAPI

````yaml POST /batch/jobs/{batch_job_id}/cancel
openapi: 3.1.0
info:
  title: TalkifAI API
  version: 1.0.0
  description: Build and manage AI voice and chat agents programmatically.
servers:
  - url: https://api.talkifai.dev
    description: Production
security:
  - bearerAuth: []
tags:
  - name: Agents
    description: Create and manage voice and chat agents
  - name: Voice Calls
    description: Initiate outbound calls and retrieve call data
  - name: Text Chat
    description: Text chat sessions via REST + SSE
  - name: Batch Calling
    description: Run large-scale outbound call campaigns
paths:
  /batch/jobs/{batch_job_id}/cancel:
    post:
      tags:
        - Batch Calling
      summary: Cancel Batch Job
      description: >-
        Cancel a scheduled, pending, or running batch job. Stops new calls and
        marks remaining contacts as cancelled.
      operationId: cancelBatchJob
      parameters:
        - name: batch_job_id
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Batch job cancelled
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                    example: true
                  message:
                    type: string
                    example: Scheduled job cancelled successfully
                  batchJobId:
                    type: string
                  redisJobCancelled:
                    type: boolean
                  contactsCancelled:
                    type: integer
        '400':
          description: Cannot cancel job in terminal status
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
              example:
                detail: Cannot cancel job in 'completed' status
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          description: Batch job not found
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '500':
          description: Internal server error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
      security:
        - bearerAuth: []
components:
  schemas:
    Error:
      type: object
      properties:
        success:
          type: boolean
          example: false
        error:
          type: string
          example: Error message
        code:
          type: string
          example: ERROR_CODE
  responses:
    Unauthorized:
      description: Invalid or missing API key
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          example:
            success: false
            error: Invalid API key
            code: invalid_api_key
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: tk_live_...
      description: Your TalkifAI API key. Get it from Studio â†’ Settings â†’ API Keys.

````