# Identity and ingestion

Facts below were checked against Braze's docs on 2026-10-17. Recheck limits and field names live before quoting them to a user (see `sources.yaml`).

## External ID rules

- One stable external_id per person, the same value from every SDK, backend sender, import and reverse ETL sync. Propose the source-of-truth entry for it in `martech-context/data-dictionary.md` and write it only after the user approves.
- Braze recommends random UUIDs. It advises against email addresses, usernames, visible profile IDs and incrementing numbers, and says not to use guessable values. Braze offers hashing an existing identifier as an alternative, together with SDK authentication, and says to normalise the hash input first (for an email: trim leading and trailing spaces, account for localisation).
- `EXTERNAL_USER_ID_TOO_LARGE` is returned above 987 bytes.
- Once set, an external_id cannot be removed from a profile, and an identified user cannot be made anonymous again. Renaming goes through `/users/external_ids/rename`, which is a write: draft the mapping file and stop for approval.
- Braze documents `alias_name` as case-sensitive (a mismatch fails silently on `/users/identify`). It does not document whether external_id matching is case-sensitive. Normalise external_id at the source and confirm case handling live if the source system is case-insensitive.

## When changeUser runs

- Call `changeUser` after the user logs in or is otherwise identified, on every platform the app ships.
- Calling it with the ID already set has no effect on session count. A different ID ends the current session, flushes pending data for the previous user and starts a new session.
- Never call `changeUser` at logout and never use a static default ID. Braze says this logs everyone's data against one user and prevents re-engaging people on shared devices.
- Logout, per Braze's data collection page (2026-10-17):
  - `logout()` unregisters push and, when that succeeds, wipes local SDK data and disables the SDK. `unregisterPush()` removes the push token only. The page lists Web SDK 6.10.0 as the minimum for `logout()`; confirm the Android and Swift minimums live against the installed versions, and use the platform-specific method from the docs on older versions.
  - After a successful `logout()`, turn the SDK back on before the next login: on Web call `enableSDK()` and then `initialize()` again; on Android call `enableSDK()`; on Swift set `enabled = true`. Then re-register for push. Without this, the next user's events on a shared device are dropped and they get no push.
  - Do not call `logout()` or `unregisterPush()` straight after registering for push with the OS or push provider; Braze warns against it.
  - A push already in flight can still arrive.
- To avoid anonymous tracking entirely, delay SDK initialisation until the first login only. Delaying it at every sign-out or session interferes with in-app message and Content Card prefetching.

### Shared-ID detection

- Search the codebase for `changeUser(` calls in logout handlers and for literal fallbacks such as `"0"`, `"guest"`, `"anonymous"`, `"null"` or `"undefined"`.
- In Braze, build a segment on Session Count with a very high threshold and inspect the top profiles. Braze blocks "dummy users" with more than 5,000,000 sessions, more than 20,000 distinct custom event names or more than 20,000 distinct purchase product names, then stops ingesting all inbound SDK and REST data for them (user data page in `sources.yaml`). A `/users/track` error saying the external_id is blacklisted points here.

## Identity specimen

Run each transition on every SDK platform with a test device and test profile. For each, record the expected profile, the observed profile and the evidence.

Before the run, add every test profile and test device to an internal group with User Events recording turned on. Braze shows SDK and REST API logs in the Event User Log only for members of such a group, so without this step the Event User Log evidence below stays empty.

1. Anonymous use
   - Action: open the app or site, trigger two events, do not log in.
   - Expected: one anonymous profile (External User ID is blank) holding the events.
   - Evidence: Event User Log filtered to SDK, the app and the test user; the profile in Search Users by Braze ID.
2. First signup with a new external_id
   - Action: sign up, `changeUser("<new uuid>")`.
   - Expected: Braze merges the anonymous profile's data into the new identified profile.
   - Evidence: the step 1 events on the identified profile.
3. Known user on a second device
   - Action: on a fresh device, browse anonymously, then log in as the step 2 user.
   - Braze's page says both that an anonymous user calling `changeUser` with an existing ID is not merged, and that fields not already populated on the identified profile are merged for a known user on a new device. Record what actually happened on each platform and SDK version. Do not promise marketing that pre-login activity on a new device reaches the profile.
4. Logout
   - Action: log out through the app's real logout path.
   - Expected: no `changeUser` call; push token removed from the profile when `logout()` or `unregisterPush()` is used; after a successful `logout()`, the app re-enables the SDK (and re-initialises on Web) and re-registers push before the next login.
   - Evidence: push token changelog in the profile's Engagement tab; the app's logout code path.
5. Shared-device switch
   - Action: user A logs out, user B logs in on the same device.
   - Expected: the SDK is enabled again; B's events land on B; B's push token is registered to B; A no longer receives push on that device.
   - Evidence: Event User Log rows for B from that device; push token changelog on both profiles.
6. Reinstall
   - Expected: anonymous again until `changeUser` runs.
7. Backend creates the profile first
   - Action: the signup service writes `/users/track` with the external_id before the app calls `changeUser`.
   - Documented behaviour: Braze's `/users/track` FAQ says that when the API creates the profile first, data the SDK recorded anonymously before identification is lost; only data after identification merges into the profile.
   - Run the transition anyway to confirm it on the installed SDK versions. If pre-signup history matters, let the SDK identify first; otherwise record the loss in the identity contract.

## Aliases, identify and merge

- An alias is `alias_name` (the identifier) plus `alias_label` (its type), for example a support system ID or a lead ID known before login.
- Writing to an alias-only profile through `/users/track`: for a `user_alias`, update-only mode defaults to true, so creating an alias-only profile needs `"_update_existing_only": false`.
- `/users/identify` works in two ways:
  - If a profile with that external_id exists, the alias-only, email-only or phone-only profile is combined into it and the alias-only profile is removed. If the external_id profile already has an alias with the same label, the profiles are not combined.
  - If no profile has that external_id, the external_id is added to the aliased profile, which becomes the identified profile in place. Nothing is removed.
  - Email or phone identification needs a `prioritization` array. When several profiles match, the call returns `"message": "success"` and does not combine anything.
  - A 201 confirms syntax, not that an alias matched. Read the target profile back.
  - The page on 2026-10-17 documents a default field merge and no option to switch it off. If a `merge_behavior` parameter appears in the live docs, read its default before using it.
- `/users/merge` combines a source profile into a target.
  - Processed asynchronously and in no guaranteed order.
  - The target keeps its existing values; blanks are filled from the source; message history and events are combined. Read the merge behaviour section live before merging test users, Global Control Group members or users marked for deletion.
  - The source profile is removed. No undo is documented: draft, approve, and keep a pre-merge export of both profiles.
  - Merges are not reflected in the Messaging History tab, Segment Extensions, Query Builder or Currents for features not powered by Snowflake, so diagnosis after a merge needs a pre-merge export.

## /users/track contract

### Identifiers

- Each object carries one primary identifier: `external_id`, `user_alias` or `braze_id`. More than one rejects that object.
- `email` or `phone` act as lookup keys only when no primary identifier is present; with both, email wins. With a primary identifier they are written as attributes.
- If `_update_existing_only` is omitted and the external_id does not exist, Braze creates a profile. A trailing space or a test prefix therefore creates an orphan profile instead of an error, and a case difference may too (Braze does not document external_id case sensitivity). Normalise at the source and confirm live. Senders that should only update known users set it to true and log the resulting errors.

### Limits that change a QA decision

Checked 2026-10-17; read the live `/users/track` and API limits pages before quoting numbers.

- Request size: exceeding the per-request object limit (75 combined across attributes, events and purchases on current limits) is a fatal 400 for the whole request, so batch size is a sender setting to test, not a constant.
- Rate limits depend on the contract. On new (MAU-based) pricing, limits are enforced at company level: hourly limits can be split per workspace, and burst limits are shared across all workspaces. A test workspace can therefore throttle production ingestion. The live values are under Settings > APIs and Identifiers > Dashboard (API usage dashboard).
- Rate limit headers: Braze documents `X-RateLimit-Reset` two ways. The API limits page says UTC epoch seconds; the `/users/track` page says, for MAU contracts (CY 24-25, Universal, Web, Mobile), seconds remaining before the window resets, and that on a 429 the `X-RateLimit-*` headers are replaced by `X-RateLimit-Retry-After` (seconds to wait). Sender rule:
  - On 429, wait the number of seconds in `X-RateLimit-Retry-After`.
  - If only `X-RateLimit-Reset` is present, read a value under 1,000,000,000 as seconds remaining and a larger value as an epoch timestamp.
  - Cap retries and alert when the cap is reached.
  - Over HTTP/2 the header names arrive lowercase.

### Responses

- Success: `"message": "success"` with optional `attributes_processed`, `events_processed`, `purchases_processed`. These count what was queued, not what reached a profile.
- Success with non-fatal errors: `"message": "success"` plus an `errors` array. Unaffected objects are still processed.
- The `errors` array holds two kinds of entry. Count them separately:
  - Object-level codes, which reject an object or a field in it: for example `EMAIL_BAD_FORMAT`, `BAD_EMAIL_SUBSCRIPTION_STATE`, `BAD_SUBSCRIPTION_GROUP_ID`, `BLACKLISTED_EXTERNAL_USER_ID`, `EXTERNAL_USER_ID_TOO_LARGE`. Map each to an owner and a fix.
  - Request-level status tracking entries when the request carried a `group_id`: `request_status_not_tracked` (for example a workspace not in the beta), `request_status_group_full`, `request_status_active_group_limit_exceeded`, `invalid_group_id`. Braze still processes the request's objects. Log these, but never count them as rejected objects.
- Braze does not document whether `EMAIL_BAD_FORMAT` drops only the email field or the whole object. Verify it live with a seeded fixture and record the answer, because it decides whether reconciliation counts objects or fields.
- Fatal: `message` holds the fatal error; nothing in the request is processed.
- 5xx or a timeout: the outcome is unknown. Braze stores each event object as a separate, unique event, so a blind retry of an event or purchase that Braze had already queued logs it twice and can enter an action-based Canvas twice.
  - Attribute objects that set absolute values can be resent. Increments and array add or remove operations change state on every apply, so treat them like events.
  - Events and purchases: check the business key ledger first. If the request carried its own `group_id`, look it up with `/users/track/status`: `received` of 1 means Braze accepted it. An empty result is inconclusive (unknown group, expired after 24 hours, or not tracked), so fall back to the ledger and a profile read-back.
  - Where a duplicate Canvas entry would matter, prefer an API-triggered Canvas keyed on the ledger over an action-based trigger on a retried event.
  - Braze cannot replay REST calls that failed during an incident; the sender must.

### Ordering

- Separate requests are processed asynchronously and are not guaranteed to apply in the order sent. A null followed quickly by a value for the same attribute can land as null.
- Mitigations, in order of preference:
  - Put the attribute and the event that depends on it in one request.
  - For API-triggered Canvases, put the attributes in the recipient's `attributes` object; Braze processes it before sending the Canvas.
  - Add a `group_id` (1 to 128 characters) and poll `/users/track/status` until `completed` before sending the dependent request. Beta, needs the `users.track.status` key permission, status kept 24 hours.
  - `/users/track/sync` (limited beta) gives a synchronous acknowledgement per user.

### Arrays and nested attributes

- Ownership rule: one system owns each attribute. If one sender writes a whole array and another adds items with operations, the whole-array write wipes the other sender's items at its next run. Give the array one writer, or make every writer use item-level operations and remove only items it added.
- Payload shapes, size limits and nested attribute behaviour belong to braze-api-segments-and-attributes. If it is not installed, read the user attributes object page in `sources.yaml` live before drafting array payloads.

## Ingestion log record

Every sender writes one row per rejected object and one summary row per request:

```yaml
request_id: req-2026-10-17-0001
sent_at: "2026-10-17T09:15:02Z"
http_status: 201
group_id: ingest-2026-10-17-0001        # one per request, optional
objects_sent: 75
objects_rejected: 1                      # object-level codes only
fields_rejected: 0                       # if the code drops a field, not the object
request_level_entries: [request_status_not_tracked]   # never counted as rejections
rejected:
  - object_index: 12
    source_record_id: acct-000412
    business_key: order-104233
    identifier_type: external_id
    payload_version: v3
    error_code: EMAIL_BAD_FORMAT
    resolution: corrected_and_replayed   # or excluded, pending
    replayed_at: "2026-10-17T09:40:10Z"
```

## Reconciliation

- Per run: expected records = accepted + rejected + deliberately excluded, counting only object-level codes. If the seeded `EMAIL_BAD_FORMAT` test showed that Braze drops the field and keeps the object, count that object as accepted and track the field rejection separately. A gap is an integration bug, not a marketing problem.
- Replay only rejected objects after correction. For events, check the business key ledger first so a replay cannot enter a Canvas twice.
- Read back a sample with `/users/export/ids`: up to 50 `external_ids` or `user_aliases` per request, but only one `email_address`, `phone` or `device_id` per request. For workspaces onboarded on or after 22 August 2024, `fields_to_export` is required and the base rate limit is 250 requests per minute; asking for `canvases_received` or `campaigns_received` makes the request ineligible for the faster tier. For real customers, never include email or phone in `fields_to_export`.
- Warehouse copies, Currents and data shares can lag the profile by hours, so they are not proof that a write landed.
