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

# Data Delivery

> Ship log-level delivery data (impressions, clicks, conversions, MMP postbacks, VAST events, MB delivery) from Apostra to a buyer-owned GCS bucket, S3 bucket, or Azure Blob container on a recurring cadence.

## Overview

Data Delivery is a standing subscription that pushes log-level data (LLD) from Apostra into a destination you own — your cloud storage, your IAM, your data pipeline. Unlike `/api/v2/buyer/reporting/metrics` (which returns aggregates synchronously), Data Delivery runs on a schedule, writes objects, and never makes you pull.

Two objects make it work, both scoped to an advertiser:

| Object | What it is |
| - | - |
| **Data Delivery Credential** | A named handle that tells Apostra *where* to write and how to authenticate. Probed asynchronously; carries a `status` of `PENDING`, `VALIDATED`, or `FAILED`. |
| **Data Delivery Output** | A standing subscription that says "ship `<data type>` to `<credential>` every `<cadence>` as `<format>` under `<pathPrefix>`". Multiple Outputs can share a credential. Campaign-scoped Outputs override the advertiser default for the same data type. |

Available data types: `MB_DELIVERY`, `IMPRESSIONS`, `CLICKS`, `VAST_EVENTS`, `CAPI_ATTRIBUTION`, `MMP_POSTBACKS`. Cadences: `HOURLY` (minute 0), `DAILY` (00:00 UTC), `WEEKLY` (00:00 UTC on `syncWeeklyDay`). Formats: `JSONL`, `PARQUET`, `CSV`.

Limits: up to 20 credentials and 20 Outputs per advertiser. One Output per `(dataDeliveryType, credentialName)` pair per scope — to fan a data type out to two destinations, list one Output per destination.

```
BASE = https://api.apostra.com/api/v2/buyer
AUTH = Authorization: Bearer scope3_<your_api_key>
```

## End-to-end shape

The high-level flow is the same regardless of destination:

**1. Grant Apostra access on your cloud**

Add a bucket/container that Apostra can write into and grant Apostra principal the required permissions. Details per destination below.

**2. Register the credential**

`PUT /advertisers/:advertiserId` with a `dataDelivery.credentials[]` entry. The credential lands as `status: PENDING`.

**3. Wait for the Probe**

Apostra asynchronously writes a sentinel object under `_scope3-probe/` and deletes it. The credential flips to `VALIDATED` on success or `FAILED` (with `statusError`) on failure.

**4. Attach Outputs**

`PUT /advertisers/:advertiserId` with `dataDelivery.outputs[]` referencing the credential by `credentialName`. Optionally override per campaign via `PUT /campaigns/:campaignId` `dataDelivery.outputs[]`.

**5. Receive data on the cadence**

Each Output fires on its schedule and lands objects under `<destination>/<pathPrefix>/...`. Open the bucket/container to confirm.

> [!NOTE]
>
> `dataDelivery.credentials` and `dataDelivery.outputs` are **full-replace arrays**. The request body is the new desired state — anything not listed is archived (credentials) or cleared (Outputs). Read the current state with `GET /advertisers/:advertiserId` before writing. A credential cannot be archived while any live Output (advertiser- or campaign-scoped) still references it — remove or repoint the Output first.

## Destination setup

> [tab] Google Cloud Storage
>
> ### 1. Grant access on your bucket
>
> Apostra authenticates to GCS with a single service account. Grant it `roles/storage.objectCreator` on the bucket you want data shipped into. No keys or secrets are exchanged.
>
> **Apostra service account:**
>
> ```
> report-delivery@swift-catfish-337215.iam.gserviceaccount.com
> ```
>
> Grant via `gcloud`:
>
> ```bash theme={null}
> gcloud storage buckets add-iam-policy-binding gs://my-apostra-data \
>   --member="serviceAccount:report-delivery@swift-catfish-337215.iam.gserviceaccount.com" \
>   --role="roles/storage.objectCreator"
> ```
>
> ### 2. Register the credential
>
> ```bash theme={null}
> curl -X PUT "$BASE/advertisers/12345" \
>   -H "Authorization: Bearer scope3_<your_api_key>" \
>   -H "Content-Type: application/json" \
>   -d '{
>     "dataDelivery": {
>       "credentials": [
>         {
>           "name": "primary-gcs",
>           "config": {
>             "type": "GCS",
>             "bucket": "my-apostra-data"
>           }
>         }
>       ]
>     }
>   }'
> ```
>
> `name` must be unique among live credentials on this advertiser. Outputs will reference it by this name.

> [tab] Amazon S3
>
> ### 1. Grant access via bucket policy
>
> Apostra authenticates to S3 with a shared IAM user. Add a statement to your bucket policy granting that principal `s3:PutObject` and `s3:DeleteObject` on objects under the path prefix you'll use. No per-buyer access keys are needed.
>
> **Apostra IAM principal:**
>
> ```
> arn:aws:iam::948454267882:user/scope3-data-sync-service
> ```
>
> Example bucket policy statement (replace `my-apostra-data`):
>
> ```json theme={null}
> {
>   "Sid": "AllowApostraDataDelivery",
>   "Effect": "Allow",
>   "Principal": {
>     "AWS": "arn:aws:iam::948454267882:user/scope3-data-sync-service"
>   },
>   "Action": [
>     "s3:PutObject",
>     "s3:DeleteObject"
>   ],
>   "Resource": "arn:aws:s3:::my-apostra-data/*"
> }
> ```
>
> `s3:DeleteObject` is recommended so the Probe can clean up its `_scope3-probe/` sentinel objects; with `s3:PutObject` only, sentinels accumulate but the credential still validates.
>
> ### 2. Register the credential
>
> ```bash theme={null}
> curl -X PUT "$BASE/advertisers/12345" \
>   -H "Authorization: Bearer scope3_<your_api_key>" \
>   -H "Content-Type: application/json" \
>   -d '{
>     "dataDelivery": {
>       "credentials": [
>         {
>           "name": "primary-s3",
>           "config": {
>             "type": "S3",
>             "bucket": "my-apostra-data",
>             "region": "us-east-1"
>           }
>         }
>       ]
>     }
>   }'
> ```
>
> `region` accepts any commercial AWS region (e.g., `us-east-1`, `eu-west-1`). GovCloud and ISO partitions are not currently supported — contact Apostra if you need them.

> [tab] Azure Blob Storage
>
> ### 1. Mint a SAS for the container
>
> Apostra authenticates to Azure with a **Shared Access Signature (SAS)**. Either flavor works — pick the one your security tooling produces.
>
> In both flavors, the required permissions are **Create + Write + Delete** (`sp` includes `c`, `w`, `d`). The Probe and delivery worker perform `PUT Blob`, block uploads, and `DELETE Blob` — they do not use Append or List.
>
> #### Option A — Service SAS scoped to the container (recommended)
>
> Narrower grant; the SAS is scoped to one container, with no implicit account-level access.
>
> ```bash theme={null}
> az storage container generate-sas \
>   --account-name datareports \
>   --name apostra-data \
>   --permissions cwd \
>   --expiry 2027-01-01T00:00:00Z \
>   --https-only \
>   --output tsv
> ```
>
> The resulting SAS has `sr=c&sp=cwd` — `sr=c` scopes it to the container and `sp=cwd` authorizes blob operations inside it. **No `srt` field.**
>
> > [!WARNING]
> >
> > A **blob-scoped Service SAS** (`sr=b`) does **not** work. The Probe writes to a randomized `_scope3-probe/<uuid>.txt` path; a blob-scoped SAS is limited to one fixed blob name and the URLs will not match. Always scope Service SAS to the container (`sr=c`).
>
> #### Option B — Account SAS
>
> If your org policy requires Account SAS instead, the `srt` field **must include `o` (Object)** — the Probe and the delivery worker perform object-level operations (`PUT Blob`, `DELETE Blob`). `srt=co` is the common shape; `srt=o` alone also works.
>
> ```bash theme={null}
> az storage account generate-sas \
>   --account-name datareports \
>   --services b \
>   --resource-types co \
>   --permissions cwd \
>   --expiry 2027-01-01T00:00:00Z \
>   --https-only \
>   --output tsv
> ```
>
> The resulting SAS has `ss=b&srt=co&sp=cwd`. `srt=s` (Service only) or `srt=c` (Container only) **will not work** — Container-only authorizes operations *on* the container resource, not on the blobs inside it.
>
> > [!WARNING]
> >
> > The SAS token is a secret. Submit only over HTTPS and never paste it into shared docs or tickets. Apostra stores it encrypted, redacts it from all `GET` responses, and surfaces only the parsed `expiresAt` back.
>
> ### 2. Register the credential
>
> ```bash theme={null}
> curl -X PUT "$BASE/advertisers/12345" \
>   -H "Authorization: Bearer scope3_<your_api_key>" \
>   -H "Content-Type: application/json" \
>   -d '{
>     "dataDelivery": {
>       "credentials": [
>         {
>           "name": "primary-azure",
>           "config": {
>             "type": "AZURE_BLOB",
>             "storageAccountName": "datareports",
>             "containerName": "apostra-data",
>             "auth": {
>               "mode": "SAS_TOKEN",
>               "sasToken": "sv=2022-11-02&se=2027-01-01T00%3A00%3A00Z&sr=c&sp=cwd&sig=..."
>             }
>           }
>         }
>       ]
>     }
>   }'
> ```
>
> Leading `?` on the SAS is tolerated and stripped. The `se=` claim is parsed and surfaced as `credential.expiresAt` — see [Rotation](#rotation) below.

## Probe lifecycle

When a credential is created or its config changes, Apostra kicks off an async **Probe** workflow keyed on the credential. The Probe writes a sentinel object to the destination, deletes it, and updates the credential row:

| `status` | Meaning |
| - | - |
| `PENDING` | Just created or rotated; Probe hasn't completed yet. Typically clears within seconds. |
| `VALIDATED` | Probe wrote and deleted a sentinel object. `validatedAt` reflects the run. |
| `FAILED` | Probe could not write. `statusError` carries a human-readable reason. |

Check status with:

```bash theme={null}
curl "$BASE/advertisers/12345" \
  -H "Authorization: Bearer scope3_<your_api_key>"
# inspect dataDelivery.credentials[].status / statusError
```

Re-run the Probe without re-submitting the credential:

```bash theme={null}
curl -X POST "$BASE/advertisers/12345/data-delivery-credentials/primary-gcs/validate" \
  -H "Authorization: Bearer scope3_<your_api_key>"
```

> [!NOTE]
>
> Outputs can reference a credential in any status. The shipping workflow re-checks at run time, so a credential that flips to `FAILED` will block its Outputs until you fix it; one that flips back to `VALIDATED` resumes automatically.

## Attaching Outputs

Outputs live alongside credentials in the same `dataDelivery` block. The example below ships hourly impressions and daily clicks to the same GCS credential, with each data type writing under a distinct path prefix.

```bash theme={null}
curl -X PUT "$BASE/advertisers/12345" \
  -H "Authorization: Bearer scope3_<your_api_key>" \
  -H "Content-Type: application/json" \
  -d '{
    "dataDelivery": {
      "outputs": [
        {
          "dataDeliveryType": "IMPRESSIONS",
          "cadence": "HOURLY",
          "credentialName": "primary-gcs",
          "deliveryConfig": {
            "type": "GCS",
            "pathPrefix": "apostra/impressions/",
            "format": "PARQUET"
          }
        },
        {
          "dataDeliveryType": "CLICKS",
          "cadence": "DAILY",
          "credentialName": "primary-gcs",
          "deliveryConfig": {
            "type": "GCS",
            "pathPrefix": "apostra/clicks/",
            "format": "JSONL"
          }
        }
      ]
    }
  }'
```

### Rules to know

* **`credentialName` must point at a live credential on the same advertiser.** The `deliveryConfig.type` must match the credential's `destinationType` (you can't ship to S3 through a GCS credential).
* **One Output per `(dataDeliveryType, credentialName)`.** To send the same data type to two destinations, list two Outputs with different credentials.
* **`syncWeeklyDay` is required when `cadence: "WEEKLY"`** (0 = Sunday, 6 = Saturday). Ignored for HOURLY/DAILY.
* **`pathPrefix` is used verbatim** — leading slashes are not stripped and the prefix is not templated. End it with `/` if you want a directory-like layout.
* **`enabled: false`** pauses the schedule without removing the Output. In-flight runs complete; no new runs fire until you flip it back.

### Campaign-scoped overrides

For a single campaign that needs a different cadence, format, or destination than its advertiser default, set `dataDelivery.outputs` on the campaign:

```bash theme={null}
curl -X PUT "$BASE/campaigns/99999" \
  -H "Authorization: Bearer scope3_<your_api_key>" \
  -H "Content-Type: application/json" \
  -d '{
    "dataDelivery": {
      "outputs": [
        {
          "dataDeliveryType": "IMPRESSIONS",
          "cadence": "HOURLY",
          "credentialName": "primary-gcs",
          "deliveryConfig": {
            "type": "GCS",
            "pathPrefix": "apostra/campaign-99999/impressions/",
            "format": "PARQUET"
          }
        }
      ]
    }
  }'
```

The override replaces the advertiser-scoped Output for the matching `dataDeliveryType` on this campaign only. Resolved Outputs in `GET` responses are tagged with `source: "advertiser"` or `source: "campaign"` so it's clear which level produced each entry.

## `MB_DELIVERY` columns

An `MB_DELIVERY` Output ships one row per seller report for each media buy that belongs to the advertiser (or the campaign, for a campaign-scoped Output) and has a reporting date inside the delivery window. Sellers often re-send the same day, so a day can appear in more than one row; `received_at` and `reporting_job_correlation_id` tell the reports apart. Only media buys on campaigns that are currently owned by the advertiser and not archived are included.

Timestamps are UTC, formatted `YYYY-MM-DDTHH:MM:SSZ`. `reporting_date` is a `YYYY-MM-DD` date. Columns a seller did not report are empty.

| Column | Type | What it holds |
| - | - | - |
| `reporting_job_correlation_id` | string | Identifies the seller report this row came from. |
| `received_at` | timestamp | When Apostra received the report. |
| `notification_type` | string | `scheduled`, `final`, `delayed` or `adjusted`. |
| `sequence_number` | integer | The seller's running number for its reports. |
| `next_expected_at` | timestamp | When the seller expects to send its next report. |
| `reporting_period_start`, `reporting_period_end` | timestamp | The period the report covers. |
| `reporting_date` | date | The day the report covers, taken from the period start. |
| `partial_data` | boolean | The report is missing data for some media buys. |
| `unavailable_count` | integer | How many media buys in the report had delayed or missing data. |
| `currency` | string | ISO 4217 currency of the money columns. |
| `storefront_media_buy_id` | string | The seller's ID for the media buy: the [storefront media buy ID](https://docs.apostra.com/v2/concepts/glossary.md). Use it to match rows to the same media buy across reports. |
| `buyer_media_buy_id` | string | Your own media buy ID. Empty when Apostra could not match the report to one of your media buys. |
| `campaign_id` | string | The campaign the media buy belongs to. |
| `seat_id` | integer | The advertiser's ID. |
| `status` | string | `active`, `completed`, `paused`, `failed` or `reporting_delayed`. |
| `expected_availability` | timestamp | When delayed data is expected to be available. |
| `is_adjusted` | boolean | The row revises data the seller sent earlier. |
| `pricing_model` | string | `cpm`, `vcpm`, `cpc`, `cpcv`, `cpv`, `cpp` or `flat_rate`. |
| `effective_rate` | number | The rate actually paid per unit. |
| `impressions`, `clicks`, `views`, `completed_views`, `conversions`, `leads`, `video_completions`, `engagements`, `follows`, `saves`, `profile_visits` | integer | Delivery totals for the media buy in this report. |
| `spend` | number | Seller-reported spend, net of the Apostra buyer fee, in `currency`. |
| `conversion_value` | number | Total value of attributed conversions, in `currency`. |
| `ctr`, `completion_rate`, `engagement_rate`, `roas`, `new_to_brand_rate`, `cost_per_acquisition`, `cost_per_click` | number | Rates and costs the seller reported or derived from the totals. |
| `grps`, `reach`, `reach_unit`, `frequency` | number, integer, string, number | Audience measures. `reach_unit` is `individuals`, `households`, `devices`, `accounts`, `cookies` or `custom`. |
| `viewed_seconds`, `attention_seconds`, `attention_score` | integer, integer, number | Viewing and attention measures. |
| `viewability` | record | The viewability measurement the seller reported. |
| `by_package` | record | The same measures broken down by package. |
| `daily_breakdown` | record | The same measures broken down by day. |
| `errors` | record | Errors or warnings from processing the report. |
| `processed_at` | timestamp | When Apostra finished processing the report. |
| `export_version` | string | The version of the export logic that produced the row. |

The `IMPRESSIONS`, `CLICKS` and `CAPI_ATTRIBUTION` Outputs keep a `media_buy_id` column. It holds whatever media buy ID the ad server put in the tracking pixel, which can be your ID, the storefront's ID or the seller's own ID, so it is not renamed.

## Rotation

### GCS and S3

No rotating secret to manage — Apostra's identity is fixed, so as long as the IAM grant stays in place the credential keeps working. Rotating means changing the bucket: submit a new credential with the new `bucket` and the existing credentials inline-array will update in place.

### Azure Blob

SAS tokens carry an expiry. The expiry from the `se=` claim is parsed and exposed on the credential response as `expiresAt` — watch it and rotate ahead of time.

To rotate, submit a fresh credential **with the same `name`**:

```bash theme={null}
curl -X PUT "$BASE/advertisers/12345" \
  -H "Authorization: Bearer scope3_<your_api_key>" \
  -H "Content-Type: application/json" \
  -d '{
    "dataDelivery": {
      "credentials": [
        {
          "name": "primary-azure",
          "config": {
            "type": "AZURE_BLOB",
            "storageAccountName": "datareports",
            "containerName": "apostra-data",
            "auth": { "mode": "SAS_TOKEN", "sasToken": "<new SAS>" }
          }
        }
      ]
    }
  }'
```

Updating in place preserves the `credentialId`, so any Output that references this credential by name keeps shipping without interruption. A fresh Probe runs against the new SAS; an in-flight Probe for the old SAS is cancelled.

## Troubleshooting

### Credential stuck on `PENDING`

The Probe workflow typically completes within seconds. If it's been more than a minute:

1. Re-fetch the advertiser — the row may have already flipped.
2. Call the revalidate endpoint to force a fresh Probe.
3. If it stays `PENDING`, contact Apostra support — the Probe worker may be backed up.

### `status: FAILED` — common `statusError` patterns

| Destination | `statusError` includes... | Fix |
| - | - | - |
| GCS | `permission`, `403`, `does not have storage.objects.create` | Grant `roles/storage.objectCreator` to `report-delivery@swift-catfish-337215.iam.gserviceaccount.com` on the bucket. |
| GCS | `bucket ... does not exist` | Check the bucket name in `config.bucket` matches an existing bucket in the project that hosts the SA. |
| S3 | `AccessDenied`, `403` | Confirm the bucket policy grants `s3:PutObject` to `arn:aws:iam::948454267882:user/scope3-data-sync-service` on `Resource: arn:aws:s3:::<bucket>/*`. |
| S3 | `PermanentRedirect`, `region` mismatch | `config.region` must match the bucket's actual region. |
| S3 | `NoSuchBucket` | Bucket name typo, or the bucket isn't in a commercial AWS partition. |
| Azure | `Azure SAS token expired at ...` | The `se=` claim is in the past. Mint a new SAS and update the credential. |
| Azure | `AuthenticationFailed` | SAS signature is wrong (truncated paste, wrong `sv=` version, signed against a different key). Regenerate. |
| Azure | `AuthorizationPermissionMismatch` | SAS is valid but missing required permissions. Confirm `sp` includes `c`, `w`, `d` (`sp=cwd`). For Account SAS, also confirm `ss=b`. |
| Azure | `AuthorizationResourceTypeMismatch` | **Account SAS only** — `srt` is missing `o` (Object). The Probe and delivery worker perform blob-level operations, so `srt` must include `o` (e.g., `srt=co`). `srt=s` or `srt=c` alone will not work. Regenerate. |
| Azure | `AuthorizationFailure` on `PUT /<container>/_scope3-probe/<uuid>.txt` | Service SAS was scoped to a single blob (`sr=b`) instead of the container (`sr=c`). Regenerate with `az storage container generate-sas` so the SAS covers any blob name under the container. |
| Azure | `ContainerNotFound` | `containerName` doesn't exist on the storage account, or the SAS was issued at a different scope. |

### Output created but no objects landing

1. Verify the referenced credential is `VALIDATED`.
2. Check `enabled` on the Output — if `false`, the schedule is paused.
3. For HOURLY cadence, allow a full hour boundary to pass before the first run. DAILY fires at 00:00 UTC, WEEKLY at 00:00 UTC on `syncWeeklyDay`.
4. Confirm there is delivery data for the period — a campaign with zero impressions on a given day produces no objects, not an empty file.

### Conflicting Outputs

If `PUT` returns a validation error about duplicate `(dataDeliveryType, credentialName)` pairs, it's because the inline array contains two Outputs with the same data type pointing at the same credential. Use distinct credentials, or merge into a single entry.

## Related

* [Reporting Overview](https://docs.apostra.com/v2/guides/reporting-overview.md) — pull-style aggregate metrics (the synchronous counterpart to Data Delivery).
* [Log Events](https://docs.apostra.com/v2/guides/log-events.md) — push events *into* Apostra (the inbound counterpart to outbound Data Delivery).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.