> For the complete documentation index, see [llms.txt](https://docs.tagshelf.dev/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.tagshelf.dev/correlation-ids.md). Agents can also search and read this documentation through its [MCP server](https://docs.tagshelf.dev/~gitbook/mcp).

# Correlation IDs

Tag a job with your own reference, such as an invoice number, then match Alfred's results and events to your records and find the job again.

A correlation ID is your own reference for the operation behind a job, such as an invoice number or an order ID. You send it when you create the job, and Alfred hands it back in the job, in the job list and in every job event. That way you can match Alfred's results to your own records without storing Alfred's job IDs, and you can find a job again whenever you need it.

It's optional. Jobs without one work exactly the same way.

{% hint style="info" %}
**Using an SDK?** The SDK examples on this page assume a client created as shown in [SDKs](https://docs.tagshelf.dev/sdks.md#create-a-client).
{% endhint %}

### How it works

1. You send the correlation ID when you create the job.
2. Alfred stores it exactly as you sent it.
3. You get it back in the job (summary and full view), in each item of the job list and in every job event.
4. You can list your jobs by it.

### Send a correlation ID

Put it in the JSON body as a top-level `correlation_id`, next to fields such as `urls`, `channel` and `metadata`. Two routes accept it:

* `POST /api/file/upload`, when you send documents by URL or from a remote source.
* `POST /api/job/create`, when you submit a deferred session.

A `correlation_id` inside `metadata` isn't read, and Alfred doesn't accept it as a header or a query parameter.

#### Send a document by URL

{% tabs %}
{% tab title="Python SDK" %}

```python
result = client.files.upload({
    "url": "https://example.com/invoices/INV-1042.pdf",
    "correlation_id": "erp:invoice:INV-1042",
})
print(result["job_id"], result["correlation_id"])
```

{% endtab %}

{% tab title="Node.js SDK" %}

```javascript
const queued = await alfred.files.upload({
  url: "https://example.com/invoices/INV-1042.pdf",
  correlation_id: "erp:invoice:INV-1042",
});
console.log(queued.job_id, queued.correlation_id);
```

{% endtab %}

{% tab title=".NET SDK" %}

```csharp
using System;
using AlfredApiWrapper.Domains.File.Requests;

var queued = await alfred.File.UploadAsync(new UploadRequest
{
    Url = "https://example.com/invoices/INV-1042.pdf",
    CorrelationId = "erp:invoice:INV-1042"
});
Console.WriteLine($"{queued.JobId} {queued.CorrelationId}");
```

{% endtab %}

{% tab title="cURL" %}

```bash
curl -X POST "https://app.tagshelf.com/api/file/upload" \
  -H "X-TagshelfAPI-Key: $ALFRED_API_KEY" \
  -H "User-Agent: my-integration/1.0" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://example.com/invoices/INV-1042.pdf",
    "correlation_id": "erp:invoice:INV-1042"
  }'
```

{% endtab %}
{% endtabs %}

#### Create a job from a deferred session

If you upload files into a [deferred session](https://docs.tagshelf.dev/endpoints/deferred-session.md), you send the correlation ID once, when you submit the session.

{% tabs %}
{% tab title="Python SDK" %}

```python
job = client.jobs.create({
    "session_id": "0f767925-b464-4ffa-b621-1a0aeacac256",
    "correlation_id": "erp:invoice:INV-1042",
})
print(job["job_id"], job["correlation_id"])
```

{% endtab %}

{% tab title="Node.js SDK" %}

```javascript
const job = await alfred.jobs.create({
  session_id: "0f767925-b464-4ffa-b621-1a0aeacac256",
  correlation_id: "erp:invoice:INV-1042",
});
console.log(job.job_id, job.correlation_id);
```

{% endtab %}

{% tab title=".NET SDK" %}

```csharp
using System;
using TagShelf.Alfred.ApiWrapper.Domains.Job.Requests;

var job = await alfred.Job.CreateAsync(new CreateJobRequest
{
    SessionId = Guid.Parse("0f767925-b464-4ffa-b621-1a0aeacac256"),
    Channel = "api",
    CorrelationId = "erp:invoice:INV-1042"
});
Console.WriteLine($"{job.JobId} {job.CorrelationId}");
```

{% endtab %}

{% tab title="cURL" %}

```bash
curl -X POST "https://app.tagshelf.com/api/job/create" \
  -H "X-TagshelfAPI-Key: $ALFRED_API_KEY" \
  -H "User-Agent: my-integration/1.0" \
  -H "Content-Type: application/json" \
  -d '{
    "session_id": "0f767925-b464-4ffa-b621-1a0aeacac256",
    "correlation_id": "erp:invoice:INV-1042"
  }'
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
**Good to know:** the multipart route `POST /api/file/uploadfile` doesn't take a correlation ID. When you upload files into a deferred session, send the correlation ID once, when you submit the session with `POST /api/job/create`. Opening the session with `POST /api/deferred/create` doesn't take one either.
{% endhint %}

Both routes answer `202 Accepted` and echo the value back next to the job's ID:

{% tabs %}
{% tab title="202 Accepted" %}

```json
{
  "job_id": "7a1d5c3e-9b2f-4e8a-8c61-3f2b9d0e4a17",
  "correlation_id": "erp:invoice:INV-1042"
}
```

{% endtab %}
{% endtabs %}

### The rules

| Rule               | Value                                                                                                                                               |
| ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------- |
| Type               | A string, or `null`. A number, boolean, array or object is refused.                                                                                 |
| Length             | Up to 512 characters, counted after Alfred trims the spaces around the value. A character outside the basic plane, such as an emoji, counts as two. |
| "None"             | These all mean you didn't set one: the field is absent, `null`, empty, or only spaces.                                                              |
| Characters allowed | Any. Colons, slashes, `#`, spaces inside the value and non-Latin text are all fine.                                                                 |
| Case               | Kept exactly as you sent it. `INV-1042` and `inv-1042` are different values.                                                                        |

#### If Alfred refuses it

Alfred checks the value when you send it. If it isn't valid, you get a `400 Bad Request` with one of these messages:

| Message                                          | When                                                    |
| ------------------------------------------------ | ------------------------------------------------------- |
| `correlation_id must be a string or null.`       | The value is a number, boolean, array or object.        |
| `correlation_id must be at most 512 characters.` | The value is longer than 512 characters after trimming. |

The key that holds the message depends on the route. It's `message` on `POST /api/job/create` and on `GET /api/job/all` (the list route gives the length message too), and `Message` on `POST /api/file/upload`.

{% hint style="info" %}
**Good to know:** some error responses also contain a `correlation_id`, a 12-character reference you can give to support. It has the same name but nothing to do with the value you send. It identifies that one error, not your job.
{% endhint %}

### What Alfred does with it

* Alfred never changes the value and never makes one up for you. A job without one stays without one.
* Alfred doesn't check that it's unique. Several jobs can share the same correlation ID, and if you send the same documents twice with the same value, you get two jobs.
* The job keeps it through restart, retry and cancel, because those actions work on the same job.
* You can't change it after the job exists. If you need a different value, create a new job.

### Where you get it back

| Where                                                              | Field                                  |
| ------------------------------------------------------------------ | -------------------------------------- |
| The `202` of `POST /api/file/upload` and of `POST /api/job/create` | `correlation_id`, next to `job_id`     |
| The job, in both views: `GET /api/job/detail/{id}`                 | `correlation_id`                       |
| Each item of `GET /api/job/all`                                    | `correlation_id`                       |
| Job events                                                         | `correlation_id` in the `event` object |

A job without a correlation ID shows an empty string, `"correlation_id": ""`, in REST responses. Webhook and real-time job events send `"correlation_id": null` instead, so check for both when you handle a job that may have none.

These job events carry it (see [Job events](https://docs.tagshelf.dev/event-api/jobevents.md) for each one):

| `event_name`                    | Sent when                                                             |
| ------------------------------- | --------------------------------------------------------------------- |
| `alfred_event_job_create`       | A job is created.                                                     |
| `alfred_event_job_start`        | The job starts.                                                       |
| `alfred_event_job_stage_update` | The job moves to a new stage.                                         |
| `alfred_event_job_finished`     | The job completes.                                                    |
| `alfred_event_job_failed`       | The job fails.                                                        |
| `alfred_event_job_retry`        | Today, this is the name a job sends when it has used all its retries. |
| `alfred_event_job_invalid`      | The job is invalid.                                                   |
| `alfred_event_job_cancelled`    | The job is cancelled.                                                 |
| `alfred_event_job_expired`      | The job expires.                                                      |

#### Where it isn't

Files don't have a correlation ID. It isn't in the file responses, and file events don't carry it. To get from a file event back to your record, read the event's `job_id`, then look at that job: it has your `correlation_id`.

### Find jobs by correlation ID

Ask `GET /api/job/all` for the jobs that share a correlation ID. This is also the call to make when you don't know whether a job arrived, for example after your request timed out.

{% tabs %}
{% tab title="Python SDK" %}

```python
page = client.jobs.get_all(correlation_id="erp:invoice:INV-1042")
print(page["total"], "jobs")
for job in page["items"]:
    print(job["id"], job["stage"], job["correlation_id"])
```

{% endtab %}

{% tab title="Node.js SDK" %}

```javascript
const page = await alfred.jobs.getAll({ correlation_id: "erp:invoice:INV-1042" });
console.log(page.total, "jobs");
for (const job of page.items) console.log(job.id, job.stage, job.correlation_id);
```

{% endtab %}

{% tab title=".NET SDK" %}

```csharp
using System;
using TagShelf.Alfred.ApiWrapper.Domains.Job.Requests;

var page = await alfred.Job.GetAllAsync(new JobListRequest
{
    CorrelationId = "erp:invoice:INV-1042"
});
Console.WriteLine($"{page.Total} jobs");
foreach (var job in page.Items) Console.WriteLine($"{job.Id} {job.Stage} {job.CorrelationId}");
```

{% endtab %}

{% tab title="cURL" %}

```bash
curl -G "https://app.tagshelf.com/api/job/all" \
  --data-urlencode "correlation_id=erp:invoice:INV-1042" \
  -H "X-TagshelfAPI-Key: $ALFRED_API_KEY" \
  -H "User-Agent: my-integration/1.0"
```

{% endtab %}
{% endtabs %}

How the lookup behaves:

* It's an exact match and it's case-sensitive. There are no prefixes or wildcards.
* Alfred trims your value first, so `%20INV-1042%20` finds the same jobs as `INV-1042`.
* A blank value is ignored. Alfred returns the normal job list, not an empty one.
* An unknown ID isn't an error: you get `200 OK` with an empty page (`"items": []` and `"total": 0`), not `404`.
* You can combine it with `channel`, `startDate` and `endDate`, `view`, paging and `sortDirection`. Results are ordered by last update.
* A job from a deferred session shows up once you submit the session.
* You only see your company's jobs.

Let your HTTP library or SDK encode the value. Characters such as `&`, `#`, `+` and spaces must be percent-encoded, or the server reads them as a separator, a fragment or a space. The cURL example above does it with `--data-urlencode`. The full list of parameters is on [List jobs](https://docs.tagshelf.dev/endpoints/job.md).

### Match events to your records

The usual pattern: your system sends an invoice with its own ID as the correlation ID, then waits for the job-finished event. When it arrives, read `correlation_id` from the event, find the invoice in your own database, and fetch the job's results.

Webhook deliveries wrap the event in an envelope, and a job without a correlation ID carries `null`:

```json
{
  "event_id": "Rt5uVn2WcYe8",
  "event_type": "job_event",
  "event_time": 1793697667.204,
  "event": {
    "event_name": "alfred_event_job_finished",
    "company_id": "3b0c5a42-6f1e-4d7b-9a58-2c71e0f4d9a6",
    "company_name": "Example Company",
    "job_id": "7a1d5c3e-9b2f-4e8a-8c61-3f2b9d0e4a17",
    "correlation_id": "erp:invoice:INV-1042",
    "creation_date": "2026-11-03T09:15:02.31",
    "update_date": "2026-11-03T09:21:07.05",
    "timestamp": "0001-01-01T00:00:00"
  }
}
```

With the real-time client, your handler receives the `event` object itself. Real-time delivers every job event of your company, so filter on the event name and the correlation ID:

{% tabs %}
{% tab title="Python SDK" %}

```python
import os

from alfred.base.config import Configuration
from alfred.base.constants import JobEvent
from alfred.http.typed import AuthConfiguration
from alfred.realtime import AlfredRealTimeClient


def on_job_finished(event):
    correlation_id = event.get("correlation_id")
    if not correlation_id:
        return  # a job that was sent without one
    print("finished:", event["job_id"], correlation_id)
    # Look up your own record with correlation_id here.


rt = AlfredRealTimeClient(
    Configuration.v1(),
    AuthConfiguration({"api_key": os.environ["ALFRED_API_KEY"]}),
)
rt.on(JobEvent.JOB_FINISHED_EVENT, on_job_finished)

try:
    rt.socket.wait()
except KeyboardInterrupt:
    pass
finally:
    rt.disconnect()
```

{% endtab %}

{% tab title="Node.js SDK" %}

```javascript
import { AlfredEvent, AlfredRealTimeClient, Configuration, Environment } from "@tagshelf/alfred";

const realtime = new AlfredRealTimeClient(
  Configuration.v1(Environment.Production),
  process.env.ALFRED_API_KEY ?? ""
);

realtime.onJobEvent((event) => {
  if (event.event_name !== AlfredEvent.JobFinished) return;
  if (!event.correlation_id) return; // a job that was sent without one
  console.log("finished:", event.job_id, event.correlation_id);
  // Look up your own record with event.correlation_id here.
});

await realtime.waitUntilConnected();
// When you're done listening: realtime.disconnect();
```

{% endtab %}

{% tab title=".NET SDK" %}

```csharp
using System;
using TagShelf.Alfred.ApiWrapper.Core;
using TagShelf.Alfred.ApiWrapper.RealTime;

var key = Environment.GetEnvironmentVariable("ALFRED_API_KEY")
    ?? throw new InvalidOperationException("Set ALFRED_API_KEY first.");

using var socket = AlfredFactory.CreateRealTimeClient(key);

socket.OnJobEvent(evt =>
{
    if (evt.EventName != JobEventNames.JobFinished) return;
    var correlationId = (string)evt.Payload["correlation_id"];
    if (string.IsNullOrEmpty(correlationId)) return; // a job that was sent without one
    Console.WriteLine($"finished: {evt.JobId} {correlationId}");
    // Look up your own record with correlationId here.
});

await socket.ConnectAsync();
try { Console.ReadLine(); }   // keep listening until Enter
finally { await socket.DisconnectAsync(); }
```

{% endtab %}
{% endtabs %}

Events aren't replayed, so if your listener was offline, look the job up with `GET /api/job/all?correlation_id=...` to catch up.

### Choose good values

* Use a prefix per source system, such as `erp:invoice:INV-1042`. Two systems can then never collide.
* Use one ID per business operation. Everything Alfred does for that operation then shares one reference.
* Keep it stable. Build it from something that doesn't change, such as a document number, not from a timestamp.
* Don't put secrets or personal data in it. It comes back in every job response and event.
* It's case-sensitive, so pick one spelling and use it everywhere.

### Common questions

**Can I change it later?** No. Alfred keeps the value you sent when the job was created. To use a different value, create a new job.

**What if I send the same one twice?** Alfred creates two jobs. It doesn't check that correlation IDs are unique, and it never removes duplicates. If your request timed out and you aren't sure whether the job arrived, look it up first with `GET /api/job/all?correlation_id=...`.

**My search returns every job.** Your `correlation_id` is probably blank, or only spaces. Alfred ignores a blank value and returns the normal list. Check that your code really passes a value.

**My search finds nothing.** Check these in order. The case must match exactly. The value must match exactly, including any spaces inside it (spaces at the start and end are trimmed). The job's session must be submitted already, because a deferred session's job shows up in the lookup only after you submit it. Also check that you're using the API key of the company that owns the job.

**Is it the same as the `correlation_id` in an error?** No. That one is a 12-character support reference for a single error, explained in [If Alfred refuses it](#if-alfred-refuses-it).

**Do files have it?** No. Only jobs and job events do. File events carry a `job_id`, so to go from a file event to your record, read that job and take its `correlation_id`.

### What's next

* [Jobs](https://docs.tagshelf.dev/endpoints/job.md): the job views and every parameter of the job list.
* [Files](https://docs.tagshelf.dev/endpoints/file.md): sending documents by URL.
* [Event API](https://docs.tagshelf.dev/event-api.md): get events delivered to you, and see [job events](https://docs.tagshelf.dev/event-api/jobevents.md) for each one.
* [SDKs](https://docs.tagshelf.dev/sdks.md): install and set up the Python, Node.js and .NET clients.
* [Quick start](https://docs.tagshelf.dev/quick-start.md): send your first document.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.tagshelf.dev/correlation-ids.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
