> For the complete documentation index, see [llms.txt](https://docs.partssource.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.partssource.com/api/core-concepts/correlation-ids.md).

# Correlation IDs

Track and debug requests using correlation IDs

Every API request is assigned a unique correlation ID for tracking and debugging. This identifier helps trace requests through the system and is essential when working with support.

***

## What is a Correlation ID?

A correlation ID is a unique identifier assigned to each API request. It appears in:

* All API responses (`correlationId` field)
* Server-side log entries
* Error messages
* Support tickets

**Example Response:**

```json
{
  "success": true,
  "data": {
    "customer": {...}
  },
  "correlationId": "0HN7QJKV3QJ8K:00000001",
  "timestamp": "2025-10-21T14:30:00.000Z"
}
```

***

## Correlation ID Format

```
0HN7QJKV3QJ8K:00000001
└─────┬──────┘ └───┬───┘
  Connection    Request
     ID         Number
```

The format combines a connection identifier with a sequential request number, making it easy to trace related requests within the same session.

***

## Using Correlation IDs

### 1. Log Correlation IDs

Always log the correlation ID with your API calls for debugging:

```csharp
var response = await httpClient.GetAsync("/api/customers/lookup?userId=123");
var result = await response.Content.ReadFromJsonAsync<ApiResponse<Customer>>();

_logger.LogInformation(
    "API call completed. Status: {Status}, CorrelationId: {CorrelationId}",
    response.StatusCode,
    result.CorrelationId);
```

### 2. Include in Error Logs

When handling errors, always include the correlation ID:

```csharp
if (!response.IsSuccessStatusCode)
{
    var error = await response.Content.ReadFromJsonAsync<ApiError>();

    _logger.LogError(
        "API error: {Title}. Status: {Status}. CorrelationId: {CorrelationId}",
        error.Title,
        error.Status,
        error.CorrelationId);

    // Store for potential support ticket
    await SaveFailedRequest(error.CorrelationId, requestDetails);
}
```

### 3. Include in Support Requests

When contacting support, always include:

* The correlation ID
* Timestamp of the request
* Expected vs. actual behavior

**Example support message:**

```
Issue: Order creation returned 500 error
CorrelationId: 0HN7QJKV3QJ8K:00000015
Timestamp: 2025-10-21T14:30:00.000Z
Environment: Production
Expected: Order created successfully
Actual: Internal Server Error response
```

***

## Code Examples

### C\#

```csharp
public class ApiLogger
{
    private readonly ILogger<ApiLogger> _logger;

    public async Task<T> ExecuteWithLogging<T>(
        Func<Task<HttpResponseMessage>> request,
        string operationName)
    {
        var stopwatch = Stopwatch.StartNew();
        HttpResponseMessage response = null;

        try
        {
            response = await request();
            var content = await response.Content.ReadAsStringAsync();
            var result = JsonSerializer.Deserialize<ApiResponse<T>>(content);

            _logger.LogInformation(
                "API {Operation} completed. Status: {Status}, Duration: {Duration}ms, CorrelationId: {CorrelationId}",
                operationName,
                (int)response.StatusCode,
                stopwatch.ElapsedMilliseconds,
                result.CorrelationId);

            if (!result.Success)
            {
                throw new ApiException(result.Errors, result.CorrelationId);
            }

            return result.Data;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex,
                "API {Operation} failed. Status: {Status}, Duration: {Duration}ms",
                operationName,
                (int?)response?.StatusCode,
                stopwatch.ElapsedMilliseconds);
            throw;
        }
    }
}
```

### TypeScript

```typescript
interface ApiResponse<T> {
  success: boolean;
  data?: T;
  errors?: string[];
  correlationId: string;
  timestamp: string;
}

async function fetchWithLogging<T>(
  url: string,
  options: RequestInit,
  operationName: string
): Promise<T> {
  const startTime = Date.now();

  try {
    const response = await fetch(url, options);
    const result: ApiResponse<T> = await response.json();
    const duration = Date.now() - startTime;

    console.log(`API ${operationName} completed`, {
      status: response.status,
      duration: `${duration}ms`,
      correlationId: result.correlationId,
    });

    if (!result.success) {
      throw new ApiError(result.errors, result.correlationId);
    }

    return result.data!;
  } catch (error) {
    const duration = Date.now() - startTime;
    console.error(`API ${operationName} failed`, {
      duration: `${duration}ms`,
      error: error.message,
    });
    throw error;
  }
}
```

### Python

```python
import logging
import time
import requests

logger = logging.getLogger(__name__)

def fetch_with_logging(url, headers, operation_name):
    start_time = time.time()

    try:
        response = requests.get(url, headers=headers)
        result = response.json()
        duration_ms = (time.time() - start_time) * 1000

        logger.info(
            f"API {operation_name} completed. "
            f"Status: {response.status_code}, "
            f"Duration: {duration_ms:.0f}ms, "
            f"CorrelationId: {result.get('correlationId')}"
        )

        if not result.get('success'):
            raise ApiError(result.get('errors'), result.get('correlationId'))

        return result.get('data')

    except Exception as e:
        duration_ms = (time.time() - start_time) * 1000
        logger.error(
            f"API {operation_name} failed. "
            f"Duration: {duration_ms:.0f}ms, "
            f"Error: {str(e)}"
        )
        raise
```

***

## Best Practices

### 1. Store Correlation IDs with Business Transactions

```csharp
public class Order
{
    public string OrderId { get; set; }
    public string ApiCorrelationId { get; set; }  // Store for debugging
    public DateTime CreatedAt { get; set; }
}

// When creating an order
var response = await CreateOrder(orderRequest);
order.ApiCorrelationId = response.CorrelationId;
await SaveOrder(order);
```

### 2. Include in Application Logs

Structure your logs to make correlation IDs searchable:

```json
{
  "timestamp": "2025-10-21T14:30:00.000Z",
  "level": "info",
  "message": "Order created successfully",
  "orderId": "ORD-12345",
  "apiCorrelationId": "0HN7QJKV3QJ8K:00000001",
  "userId": "jsmith"
}
```

### 3. Create a Correlation ID Index

For high-volume integrations, maintain an index of correlation IDs:

```sql
CREATE INDEX idx_api_correlation ON api_requests(correlation_id);

-- Query for debugging
SELECT * FROM api_requests
WHERE correlation_id = '0HN7QJKV3QJ8K:00000001';
```

***

## Troubleshooting with Correlation IDs

When debugging an issue:

1. **Find the correlation ID** from your logs or error response
2. **Note the timestamp** of when the error occurred
3. **Gather context** - what operation was being performed?
4. **Contact support** with all this information

Support can use the correlation ID to:

* Find the exact request in server logs
* See what data was sent and received
* Identify where in the processing pipeline an error occurred
* Trace the request through multiple internal services


---

# 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 dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.partssource.com/api/core-concepts/correlation-ids.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
