# Migrate from Mixpanel

Bring your Mixpanel event history into a Cohorly project with `cohorly import mixpanel`: download the raw export, pick a credential, choose what to drop or hash, then run an import that resumes where it stopped and reports every refused event by day and reason.

Your Mixpanel history can live next to the events your apps send to Cohorly
from now on. The [Cohorly CLI](/cli) reads Mixpanel's raw event export (one
JSON event per line) and sends it to the historical import endpoint of your
project in batches. Nothing in the export is guessed or invented: the events
arrive as Mixpanel recorded them, with the few changes listed under
[What the CLI changes](#what-the-cli-changes).

The import is built for large histories (hundreds of millions of events, many
hours): it streams the files with constant memory, saves its progress after
every batch, and can be stopped and started again at any time.

## Before you start

- **Retention.** Events older than your organization's retention are refused
  as `older_than_retention`: they would be deleted by the next retention run
  anyway. Check your plan's retention before you export years of data.
- **No identity links.** Imported events are stored with the `distinct_id`
  they carry in the export. The import does not link device ids to users, does
  not resolve aliases and does not merge profiles. Events your SDKs send
  later are linked as usual.
- **Monthly quota.** Events dated in the current UTC month count toward your
  monthly event quota, like live events. When the current-month events of a
  batch do not all fit, all of them are refused as `quota` while the earlier
  months of the batch are stored. Events from earlier months do not count.
  Running the import again once your quota allows it is safe: events already
  stored are skipped as duplicates. Imports are not rate limited like live
  traffic.
- **Time zones (not verified).** Mixpanel projects created before January
  2023 may have recorded `time` in the project's time zone instead of UTC. We
  have not verified this. The CLI does not correct it: if your project is
  that old, compare a few imported events with Mixpanel before you import
  everything.

## 1. Download the raw export

Use Mixpanel's [raw event export API](https://developer.mixpanel.com/reference/raw-event-export),
authenticated with a Mixpanel service account. It answers one JSON event per
line for a date range. Export one range per file (a month per file keeps each
download manageable) and keep the files in one directory:

```bash
curl --compressed --fail \
  -u "<service-account-username>:<service-account-secret>" \
  "https://data.mixpanel.com/api/2.0/export?project_id=<mixpanel-project-id>&from_date=2024-01-01&to_date=2024-01-31" \
  -o exports/2024-01.jsonl
```

- Projects stored in Mixpanel's EU data center use
  `https://data-eu.mixpanel.com` instead.
- Add `&time_in_ms=true` to get `time` in milliseconds. Without it `time` is
  in seconds; the CLI converts seconds to milliseconds for you, so both
  exports import the same way.
- You can gzip the files (`2024-01.jsonl.gz`): the CLI reads them as they are.

The CLI reads `.json`, `.jsonl` and `.ndjson` files, each optionally
gzipped, in name order. Naming files by date (`2024-01.jsonl`,
`2024-02.jsonl`, ...) imports them in time order.

## 2. Get a credential

The import endpoint takes an organization-level credential, sent as
`Authorization: Bearer <credential>` through `--token` or the
`COHORLY_IMPORT_TOKEN` environment variable:

- **An organization API key allowed to import.** Organization owners create
  API keys in Settings, under API keys; create one with the `import` scope.
  See [API keys](/api/api-keys).
- **The admin key of a self-hosted instance** (`COHORLY_API_KEY` on the
  server).

Do not use the token of your dashboard session. It is valid for 15 minutes
and a long import outlives it: the import stops with `401` as soon as it
expires.

You also need the numeric id of the Cohorly project to import into. The
import never falls back to a default project: an import into the wrong
project cannot be undone.

## 3. Decide what to drop or hash

The export carries everything Mixpanel stored, including personal data you
may not want to keep: names, e-mail addresses, document numbers, IP
addresses. Two options change the events before they leave your machine:

- `--drop-prop <name>` removes the property from every event.
- `--hash-prop <name>` replaces its value with the SHA-256 hex of the value
  (the text itself for a string, the JSON for an object or array; `null`
  stays `null`). The same value always gives the same hash, so you can still
  count and group by it, but not read it.

Both take the exact property name, apply to the event's properties only and
can be repeated. A name passed to both is dropped.

```bash
cohorly import mixpanel --project 12 \
  --drop-prop '$name' --drop-prop ip --drop-prop document_number \
  --hash-prop '$email' --hash-prop email \
  exports/
```

Quote names that start with `$` so your shell does not expand them.

## 4. Run the import

```bash
export COHORLY_IMPORT_TOKEN=...   # never printed
cohorly import mixpanel --project 12 --report import-report.csv exports/
```

On a self-hosted instance, also set `COHORLY_API_URL` (or `--api-url`) to
your server.

The CLI prints the file it is reading and running counts (read, inserted,
duplicates, refused) at most once a second. It never prints an event. Lines
that are not valid JSON are skipped with their file and line number (the
first 20 are printed, all are counted in the report).

When the server is busy (another import is running, `429`; or it is
preparing storage for a new month, `503`), the CLI waits the time the server
asks for and sends the same batch again. Server errors and network errors
are retried with a growing delay, up to 8 attempts per batch; after that the
import stops with exit code 1.

## What the CLI changes

Each event is sent as exported, except:

- `properties.time` in seconds becomes milliseconds (only a positive whole
  number below 100,000,000,000; anything else is sent as it is and the
  server refuses it if it is not a valid time).
- `mp_lib` is copied to `$lib` when the event has no `$lib`, so Cohorly's
  library breakdowns work. `mp_lib` is kept.
- `--drop-prop` and `--hash-prop`, applied after that copy.

The CLI never adds or changes `$insert_id`. Events without one get an id the
server derives from their content.

An event larger than 8 MiB is not sent: it is reported as `event_too_large`
with its file and line, and the import goes on.

## Stop, resume and restart

After every batch the server confirms, the CLI writes
`<file>.cohorly-import.json` next to the export file: the last line of the
file whose events are stored, and the report counts up to that line. Stop the
import at any time (Ctrl+C, a lost connection, a reboot), then **run the same
command again**: it continues after the last confirmed line and skips the
files already complete. The report at the end covers the whole of every file,
both runs included.

`--restart` ignores the saved progress and imports from the first line. A
progress file written for another project, or for another API URL, stops the
import until you pass `--restart`, so a typo in `--project` or a test run
against a local server never mixes two imports. `--report` cannot point at an
export file or at a progress file.

Importing the same file again is safe. Events are deduplicated by
`$insert_id` (or the derived id), so a second import stores nothing new and
counts every event as a duplicate.

## Read the report

At the end, the CLI prints the report, and writes it to `--report` as CSV
with the same rows:

```text
day,reason,read,inserted,duplicates,refused
2023-11-14,older_than_retention,3,0,0,3
2023-11-15,,1,1,0,0
2023-11-16,,6,6,0,0
2023-11-16,missing_distinct_id,1,0,0,1
unknown,invalid_json,1,0,0,1
total,,12,7,0,5
```

- `day` is the UTC day of the event's `time`, or `unknown` when the event has
  no valid time (or the line is not JSON).
- An empty `reason` counts the events the server accepted: `inserted` new
  ones and `duplicates` it already had. `read` is their sum.
- Any other `reason` counts refused events (`read` = `refused`):
  `invalid_json` and `event_too_large` were never sent; the others come from
  the server: `invalid_event`, `missing_distinct_id`, `missing_time`,
  `invalid_time`, `time_in_seconds`, `time_in_future`,
  `older_than_retention`, `dropped_event` (an event your lexicon drops),
  `exception_event` (`$exception` events, which only the error tracking
  pipeline stores), `too_many_months` (a request may create at most 3 new
  monthly partitions, so events of further months that had none yet are
  refused and not stored; the CLI already keeps each batch within 3 months,
  so it only appears when you call the API directly: send smaller batches.
  A file sorted by time, as Mixpanel exports it, keeps the CLI's batches
  large; events of many months mixed together make it send many small ones)
  and `quota` (an event from the current month, over your monthly event
  quota).
- The `read` column adds up to the non-blank lines of your files.

The server reports inserted and duplicate counts per batch, not per event.
When one batch holds both, the per-day split between the two columns is an
estimate; the totals are exact.

The command exits with code 0 when every file was read to the end, even with
refused events, and 1 when it stopped (bad credential, a batch the server
refused, retries exhausted) or was called wrong.

## User profiles

After the events, bring the user profiles (name, e-mail, plan, any property
Mixpanel holds about a person) with `cohorly import mixpanel-profiles`. It
works like the event import: same credential, same project id, same progress
file next to each input, same report idea.

**Order.** Import the events first, then the profiles. Profiles can be
imported before or after the SDK that sends live traffic is running: a
profile import only fills in what is missing, so it never overwrites what
your apps have already sent.

### Export the profiles

Use Mixpanel's [profile query API](https://developer.mixpanel.com/reference/engage-query).
It answers pages shaped like this:

```json
{
  "results": [{ "$distinct_id": "user-42", "$properties": { "plan": "pro" } }],
  "page": 0,
  "session_id": "...",
  "status": "ok",
  "total": 1234
}
```

Save each page as a file; the CLI reads the `results` and ignores `page`,
`session_id`, `status` and `total`. It also reads a JSON array of profiles,
and a file with one profile per line (JSONL), and detects which one it got
from the content, not the file name. If the first line is a complete JSON
value that is not an array, the file is read line by line: a line that is a
whole page (what a pagination loop appending with `>>` produces) is read as
its profiles, and a line that is not JSON counts as `invalid_profile` without
stopping the file. Otherwise the file is read as one JSON document, and falls
back to line by line if it is not one. Each file can be gzipped.

We wrote this against Mixpanel's public reference, not against a real
export from your project. Run it on one small page first and read the
report before you import everything.

A page or array file is read whole, so its size has to fit in memory;
keep pages at Mixpanel's own page size. A JSONL file is streamed and can be
as large as you like.

### Run the import

```bash
export COHORLY_IMPORT_TOKEN=...   # never printed
cohorly import mixpanel-profiles --project 12 \
  --hash-prop '$email' --drop-prop ip \
  --report profiles-report.csv profiles/
```

The options are the ones of `import mixpanel`: `--project`, `--token`,
`--api-url`, `--drop-prop`, `--hash-prop` (applied to each profile's
`$properties`; a name passed to both is dropped), `--restart` and `--report`.
An organization API key with the `import` scope works for profiles too, the
same one you use for events.

`$distinct_id` and `distinct_id` cannot be dropped or hashed: the command
refuses them before it reads any file. The profile's id has to be the same
`distinct_id` your imported events carry, because that is what ties a
profile to its events. This version does not link profiles to events by any
other id. If a profile's `$distinct_id` is an alias of another id, the server
stores it on the canonical profile of that identity.

### What gets stored

- **Only what is missing.** Each profile is stored as a `$set_once`: a
  property the profile already has in Cohorly stays as it is, and only the
  absent ones are written. Importing profiles before or after your new SDK
  is live is safe.
- **No enrichment.** Cohorly does not derive a location from an IP address
  and does not stamp `$last_seen` with the time of the import.
  `$last_seen`, `$timezone` and every other property enter exactly as they
  are in the export.
- **Reimporting is safe.** Sending the same file again changes no property
  and does not change the order of the user list. A profile created by the
  import appears with the date of the import in `updated_at`.
- **Numeric ids.** A numeric `$distinct_id` is stored as text, like the
  `distinct_id` of imported events.
- **The final state only.** The export holds each profile's current state.
  Operations such as `$add`, `$unset`, `$delete` and `$union`, and group
  profiles, are not imported.

A profile with no `$distinct_id`, or a line that is not a JSON object, is not
sent: it is counted as refused (`missing_distinct_id`, `invalid_profile`)
and the import goes on.

### Resume and report

Progress is saved after every confirmed batch in `<file>.cohorly-import.json`,
counting profiles (not lines): run the same command again to resume after the
last confirmed profile. A progress file written by `import mixpanel` for the
same export file is a different kind of import: the command stops and asks
for `--restart`, which starts the file over and is safe.

The report has one row per reason:

```text
reason,read,applied,refused
,10,10,0
invalid_profile,1,0,1
missing_distinct_id,2,0,2
total,13,10,3
```

An empty `reason` counts the profiles the server applied. `invalid_profile`
and `missing_distinct_id` are refused (by the CLI before sending, or by the
server); `profile_too_large` is a profile above the 8 MiB batch limit. Like
the event import, the command exits with `0` when every file was read to the
end, even with refused profiles, and with `1` when it stopped.

## Import your Lexicon

If you documented events and properties in the Mixpanel Lexicon, bring those
names, descriptions, tags and hidden flags along, so imported history does not
arrive with raw names and no description. `cohorly import mixpanel-lexicon`
reads the Lexicon's schemas export (a JSON file) and writes it to the Cohorly
Lexicon of a project, one entry per event, event property and profile
property. It reads a file: it never downloads anything from Mixpanel.

### Get the schemas export

Mixpanel's Lexicon schemas API lists every schema of a project. With a
Mixpanel service account, request
`/api/app/projects/<mixpanel-project-id>/schemas` on the Mixpanel app host of
your data region and save the answer:

```bash
curl --fail \
  -u "<service-account-username>:<service-account-secret>" \
  "$MIXPANEL_APP_HOST/api/app/projects/<mixpanel-project-id>/schemas" \
  -o schemas.json
```

Set `MIXPANEL_APP_HOST` to the address you open Mixpanel on, scheme included,
without a trailing slash. See Mixpanel's
[Lexicon API reference](https://developer.mixpanel.com) for the current
endpoint. The CLI accepts the answer as it comes, either a plain list of
schemas or an object with a `results` list. We have not checked the format
against a real export: if your file is shaped differently, entries the CLI
cannot place are counted as unsupported in the summary instead of being
written.

### Run it

The credential is an organization API key with the `import` scope, created by
an organization owner (the key only acts as an owner while its creator is
one), or the admin key of a self-hosted instance.

```bash
export COHORLY_IMPORT_TOKEN=...   # never printed
cohorly import mixpanel-lexicon --project 12 --dry-run schemas.json
cohorly import mixpanel-lexicon --project 12 schemas.json
```

| Option            | Meaning                                                                    |
| ----------------- | -------------------------------------------------------------------------- |
| `--project <id>`  | Project to write into. Required.                                           |
| `--token <token>` | Credential (default `COHORLY_IMPORT_TOKEN`).                               |
| `--api-url <url>` | Your Cohorly server (default `COHORLY_API_URL`, else the hosted API).      |
| `--overwrite`     | Replace fields the Cohorly Lexicon already has.                            |
| `--dry-run`       | Print what would change and write nothing. Only reads the current Lexicon. |

- **Filled fields stay.** A field the Cohorly Lexicon already has (a display
  name, a description, tags, or `hidden` already on) is not overwritten;
  only the empty ones are filled. `--overwrite` replaces them. A field
  Mixpanel has no value for is never cleared, with or without `--overwrite`.
- **Never written.** `dropped`, `mergedInto` and `verified`, even when the
  export carries them. An import key can write only the display name,
  description, tags and `hidden`: the server refuses it anything else, the
  tracking plan fields included. Drop, merge and verify in the dashboard, as
  an owner.
- **Skipped and counted.** Schemas Cohorly has no Lexicon type for: groups,
  lookup tables, custom events and calculated properties. The count is of
  schemas, not of the properties inside them. An event or property Mixpanel
  documented nothing for is not an entry and is not counted.
- **Properties are keyed by name.** A property used by several events becomes
  one entry, with the first value found for each field, `hidden` included.
- **Visibility.** `hidden: true` in the export hides an entry that is not
  hidden yet. An explicit `hidden: false` makes a hidden entry visible again
  only with `--overwrite`.

The summary lists the entries created (new in the Lexicon), updated (already
there, fields added), skipped because already filled, skipped because the
type is unsupported, and failed. A failed entry does not stop the others;
the command exits with `1` if any failed. Busy answers (`429`, `503`) and
server or network errors are retried as in the event import.
