# Errors
Source: https://retain.so/docs/api-reference/errors
Troubleshoot problems with this comprehensive breakdown of all error codes
Troubleshoot problems with this comprehensive breakdown of all error codes.
## Error schema
We use standard HTTP response codes for success and failure notifications. All errors return a consistent format:
```json theme={"theme":"vesper"}
{
"message": "Human-readable error description",
"statusCode": 400,
"name": "validation_error"
}
```
Use the `name` field for programmatic error handling in your SDK or application.
## Error codes
### `validation_error`
* **Status:** 400
* **Message:** Varies. Describes which field failed validation and why.
* **Suggested action:** Check the `message` field for details. Common causes: missing required fields (`userId`, `email` for identify; `userId`, `event` for track), invalid email format, invalid URL in `avatar`, or event name containing spaces.
### `invalid_write_key`
* **Status:** 401
* **Message:** Missing or invalid Project Token.
* **Suggested action:** Include the `Authorization: Basic rk-xxxxxxxxx` header with a valid [Project Token](/docs/guides/authentication). Ensure the token starts with `rk-` and has not been revoked.
### `not_found`
* **Status:** 404
* **Message:** User not found, please identify the user first using the /identify endpoint.
* **Suggested action:** Call [POST /identify](/docs/api-reference/identify/identify-a-user) before [POST /track](/docs/api-reference/track/track-an-event). Events can only be recorded for users that have been identified.
### `rate_limit_exceeded`
* **Status:** 429
* **Message:** Too many requests. Please limit the number of requests per second.
* **Suggested action:** Reduce the rate of API requests. Consider batching events or introducing a queue. If you need higher limits, contact support.
### `application_error`
* **Status:** 500
* **Message:** An unexpected error occurred, please try again later.
* **Suggested action:** Retry the request. If the error persists, check our status page or contact support.
# Identify a user
Source: https://retain.so/docs/api-reference/identify/identify-a-user
/api-reference/openapi.json post /identify
Registers or updates a user (customer) in your organization. Call this when a user signs up or when their profile changes. You must identify a user before tracking events for them.
# Introduction
Source: https://retain.so/docs/api-reference/introduction
Overview of the Retain API for identifying users and tracking events
## Overview
The Retain API lets you send user and event data from your application. Use it to power churn prevention, health scores, and customer analytics.
## Endpoints
| Method | Endpoint | Description |
| - | - | - |
| POST | `/identify` | Register or update a user |
| POST | `/track` | Record an event for a user |
## Flow
1. **Identify** users when they sign up or when their profile changes.
2. **Track** events as users interact with key features of your product.
Always call `/identify` before `/track`. Events can only be recorded for users
that have been identified.
## Authentication
To authenticate, add an `Authorization` header with the value `Basic rk-xxxxxxxxx`, where `rk-xxxxxxxxx` is your [**Project Token**](https://retain.so/dashboard/settings?tab=project-token).
```
Authorization: Basic rk-xxxxxxxxx
```
See the [authentication guide](/docs/guides/authentication) for details.
## Response codes
Retain uses standard HTTP codes to indicate the success or failure of your requests.
In general, `2xx` codes correspond to success, `4xx` codes are for client errors (invalid request, auth, or resource not found), and `5xx` codes are for server issues.
| Status | Description |
| - | - |
| `201` | Successful request. |
| `400` | Invalid body, missing required fields, or invalid format. |
| `401` | Missing or invalid Project Token. |
| `404` | User not found. Identify the user first using `/identify` (track only). |
| `429` | Rate limit exceeded. |
| `5xx` | Indicates an error with Retain servers. |
Check [Errors](/docs/api-reference/errors) for a comprehensive breakdown of all
possible API errors, including the response format and error codes.
## Next steps
Get and use your Project Token.
Identify users in Retain.
# Track an event
Source: https://retain.so/docs/api-reference/track/track-an-event
/api-reference/openapi.json post /track
Records an event for a user. The user must have been identified first using the /identify endpoint. Events are used to calculate engagement, health scores, and churn risk.
# Connect payment provider
Source: https://retain.so/docs/connect-payment-provider
Link your payment provider so Retain can sync subscriptions, renewals, and revenue alongside your product data.
Open **[Integrations](https://retain.so/dashboard/integrations)** in the Retain dashboard, choose your provider, and follow the on-screen steps.
After you connect a payment provider, Retain ingests billing events (subscriptions, renewals, upgrades, cancellations, and more) automatically and ties them to your users.
## Matching users from payment provider
Connecting a payment provider **creates or updates customers in Retain** automatically from your billing data.
Retain matches customers from your payment provider to users in your product using a shared identifier.
Use one of these approaches so revenue and in-app behavior stay on the same customer:
1. **Same email** - The customer email from your payment provider must be the same as the one used in [`identify`](/docs/guides/identify) on Retain. Matching email addresses will link billing events with [`track`](/docs/guides/track) activity.
**Customer from your payment provider:**
```json theme={"theme":"vesper"}
{
"id": "cus_456",
"email": "jane@example.com"
}
```
**Identifing the user on Retain**:
```typescript theme={"theme":"vesper"}
retain.identify({
userId: "user_789",
email: "jane@example.com",
});
```
2. **Same `userId` in metadata** - Store your application’s **`userId`** (the same value used in [`identify`](/docs/guides/identify)) in the customer metadata of your payment provider. This ensures billing events are always linked to the correct user, even if the email is different.
**Customer from your payment provider:**
```json theme={"theme":"vesper"}
{
"id": "cus_123",
"email": "billing@email.com",
"metadata": {
"userId": "user_abc123"
}
}
```
**Identifing the user on Retain**:
```typescript theme={"theme":"vesper"}
retain.identify({
userId: "user_abc123",
email: "product@email.com",
});
```
Product and billing emails can differ. Matching `userId` links both sides.
## Native connectors
* **Stripe**
* **Polar**
* **Paddle** (coming soon)
* **Lemon Squeezy** (coming soon)
## Next steps
Choose product events to track.
# Authentication
Source: https://retain.so/docs/guides/authentication
Authenticate API requests using your Project Token
All API requests require a Project Token. The token identifies your organization and authorizes requests to identify users and track events.
## Getting your Project Token
1. Go to [Settings](https://retain.so/dashboard/settings?tab=project-token) and copy your Project Token (it starts with `rk-`)
Although the Project Token is write-only, we recommend using it only on the
backend.
## Using the Project Token
In **Node.js**, pass the token when creating the Retain client and the SDK handles authentication automatically.
In **other languages**, include the token in each request using Authorization: `Basic ` with `Content-Type: application/json`.
The same token authorizes connected sources too, so if you are forwarding events from a tool like PostHog, this is the only credential you need there as well.
```typescript Node.js icon="square-js" focus={3} theme={"theme":"vesper"}
import { Retain } from '@retain-so/sdk';
const retain = new Retain(process.env.RETAIN_WRITE_KEY);
```
```python Python icon=python focus={6-9} theme={"theme":"vesper"}
import os
import requests
requests.post(
'https://api.retain.so/identify',
headers={
'Content-Type': 'application/json',
'Authorization': f'Basic {os.environ["RETAIN_WRITE_KEY"]}',
},
json={
'userId': 'user_123',
'email': 'jane@example.com',
},
)
```
```php PHP icon=php focus={5-8} theme={"theme":"vesper"}
$ch = curl_init('https://api.retain.so/identify');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'Authorization: Basic ' . getenv('RETAIN_WRITE_KEY'),
],
CURLOPT_POSTFIELDS => json_encode([
'userId' => 'user_123',
'email' => 'jane@example.com',
]),
]);
curl_exec($ch);
curl_close($ch);
```
```ruby Ruby icon=gem focus={6-7} theme={"theme":"vesper"}
require 'net/http'
require 'json'
uri = URI('https://api.retain.so/identify')
req = Net::HTTP::Post.new(uri)
req['Content-Type'] = 'application/json'
req['Authorization'] = "Basic #{ENV.fetch('RETAIN_WRITE_KEY')}"
req.body = { userId: 'user_123', email: 'jane@example.com' }.to_json
Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) { |http| http.request(req) }
```
```java Java icon=java focus={12-13} theme={"theme":"vesper"}
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
String json = """
{"userId":"user_123","email":"jane@example.com"}
""";
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://api.retain.so/identify"))
.header("Content-Type", "application/json")
.header("Authorization", "Basic " + System.getenv("RETAIN_WRITE_KEY"))
.POST(HttpRequest.BodyPublishers.ofString(json))
.build();
HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());
```
```bash cURL focus={2-3} theme={"theme":"vesper"}
curl -X POST https://api.retain.so/identify \
-H "Content-Type: application/json" \
-H "Authorization: Basic $RETAIN_WRITE_KEY" \
-d '{
"userId": "user_123",
"email": "jane@example.com"
}'
```
See [Identify](/docs/guides/identify) and [Track](/docs/guides/track) for the same pattern with full request bodies in each language.
## Next steps
Identify users in Retain.
Record events for users.
# Connect MCP
Source: https://retain.so/docs/guides/connect-mcp
Let Claude, Cursor and other AI agents read your churn data and act on it
Retain speaks [MCP](https://modelcontextprotocol.io). Point any MCP client at [`@retain-so/mcp-server`](https://github.com/retain-so/mcp-server) and your agent can answer "who is about to churn?" without you opening a dashboard.
The server holds no business logic and no database. It translates MCP tool calls into HTTP requests against Retain's `/agent/*` API, authenticated with an agent key you create and can revoke at any time.
Agent keys are **not** the same as the Project Token used for
[ingest](/docs/guides/authentication). A **read** key can only query. A **read &
write** key can also mark alerts as contacted and archive them.
## What you can ask
Read:
* "Which customers are at critical risk this week?"
* "Show me my high-risk customers ordered by MRR."
* "What's my total MRR at risk, broken down by risk level?"
* "Pull the full profile for Acme Inc."
* "List the active alerts I haven't contacted yet."
* "Summarize this month's churn metrics and net revenue retention."
Act (needs a read & write key):
* "Mark the alert for Globex as contacted."
* "Archive the resolved alert for Initech."
## Set it up
In Retain, go to **Settings → [Agent
keys](https://retain.so/dashboard/settings?tab=agent-keys)** and create a
key. Pick **read** for query-only, or **read & write** to let the agent take
actions.
The key starts with `rk_agent_` and is shown once, so copy it before closing
the dialog.
Drop your key into the config for your client. Claude Desktop
(`claude_desktop_config.json`) and Cursor (`.cursor/mcp.json`) take the same
JSON. Codex keeps its servers in TOML, at `~/.codex/config.toml`.
```bash Claude Code theme={"theme":"vesper"}
claude mcp add retain --env RETAIN_API_KEY=rk_agent_xxx -- npx -y @retain-so/mcp-server
```
```json Claude Desktop theme={"theme":"vesper"}
{
"mcpServers": {
"retain": {
"command": "npx",
"args": ["-y", "@retain-so/mcp-server"],
"env": { "RETAIN_API_KEY": "rk_agent_xxx" }
}
}
}
```
```json Cursor theme={"theme":"vesper"}
{
"mcpServers": {
"retain": {
"command": "npx",
"args": ["-y", "@retain-so/mcp-server"],
"env": { "RETAIN_API_KEY": "rk_agent_xxx" }
}
}
}
```
```toml Codex theme={"theme":"vesper"}
[mcp_servers.retain]
command = "npx"
args = ["-y", "@retain-so/mcp-server"]
[mcp_servers.retain.env]
RETAIN_API_KEY = "rk_agent_xxx"
```
Codex can also write that entry for you:
`codex mcp add retain --env RETAIN_API_KEY=rk_agent_xxx -- npx -y @retain-so/mcp-server`.
Restart the client so it picks up the new server, then ask it who is about
to churn. A first `npx` run downloads the package, so give it a few seconds.
## Tools
| Tool | Type | What it does |
| - | - | - |
| `get_at_risk_customers` | read | Customers by churn risk, ordered by MRR |
| `get_customer_details` | read | Full profile for one customer |
| `get_mrr_at_risk` | read | MRR at risk, plus alert counts by level |
| `get_active_alerts` | read | Active alerts, with their risk factors |
| `get_churn_metrics` | read | Churn rate, MRR churned, expansion, NRR |
| `mark_alert_contacted` | write | Mark an alert as contacted |
| `archive_alert` | write | Archive a resolved alert |
`get_at_risk_customers` defaults to Critical and High risk, and `get_customer_details` takes either a customer id or a name. Coming soon: `send_retention_email`, to trigger a templated retention email.
## Configuration
| Variable | Required | Default | Description |
| - | - | - | - |
| `RETAIN_API_KEY` | yes | | Agent key from **Settings → Agent keys**. |
| `RETAIN_API_URL` | no | `https://api.retain.so` | Override the API base URL (staging, self-host). |
## Troubleshooting
* **`RETAIN_API_KEY is not set`.** The client launched the server without the env var. Check that `env` sits inside the `retain` entry in your config, not next to it.
* **`Invalid or revoked agent key`.** The key was revoked, or belongs to another organization. Create a new one in **Settings → Agent keys**.
* **`This agent key is read-only`.** The agent tried an action tool with a read key. Create a read & write key and swap it in.
* **The server never shows up.** MCP clients read their config at startup, so restart fully after editing it. The server needs Node 22 or newer.
## Next steps
Read the code, open an issue, or contribute a tool.
The Project Token used to send events, which is a different key.
# Connect PostHog
Source: https://retain.so/docs/guides/connect-posthog
Stream your existing PostHog events into Retain, no re-instrumentation needed
Already tracking product usage with PostHog? Good news: you don't need to instrument anything twice. PostHog's realtime destinations can forward your events straight to Retain, so churn signals start flowing in minutes.
Retain identifies people by **email**. Make sure your PostHog setup stores an
`email` property on person profiles (most `posthog.identify()` calls already
do this). Events from anonymous visitors are skipped.
## How it works
PostHog sends each event to Retain as it happens. Retain then:
* Turns `$identify` and `$set` events into customer profiles (email, name, and other traits)
* Records your custom events (e.g. `report exported`) as Retain events, auto-creating them on first sight
* Maps [group analytics](https://posthog.com/docs/product-analytics/group-analytics) (`$groupidentify`, `$groups`) to Retain accounts, so B2B usage rolls up correctly
* Ignores PostHog-internal events like `$pageview`, `$autocapture`, and `$feature_flag_called`
* Deduplicates retries, so a redelivered event never counts twice
Event names are normalized to snake\_case: `Report Exported` becomes `report_exported`.
## Set it up
In Retain, go to **Settings → Project token** and copy your write key (it
starts with `rk-`).
In PostHog, open **Data → Destinations → New destination**, search for
**Retain** and select it.
Paste the write key into the **Retain write key** field. That's the whole
configuration.
In the destination's **Filters**, select your key product events plus
`$identify`. Two reasons: Retain's churn detection works best on
high-signal events, and PostHog bills realtime destinations per trigger
event (the first 10k per month are free), so filtering keeps you in the
free tier.
Use PostHog's **Start testing** button to fire a test event, then enable
the destination. Events show up in Retain under
[**Events**](https://retain.so/dashboard/events), and identified users
under **Customers**.
## Configure your events
Once events arrive, set their **Importance** and **Expected frequency** on the [Events page](https://retain.so/dashboard/events) so Retain knows what healthy usage looks like. See [Track events](/docs/guides/track) for what each setting does.
## Troubleshooting
* **Events aren't showing up.** Check the destination's logs in PostHog. A `401` means the write key is wrong — copy it again from **Settings → Project token** in Retain.
* **Events arrive but no customer is created.** The person has no valid `email` in their PostHog person properties. Retain skips events it can't tie to an email.
* **An event appears with a different name.** That's the snake\_case normalization. `Signed Up` in PostHog is `signed_up` in Retain.
* **`$pageview` never arrives.** By design — PostHog-internal `$` events are ignored. Track a meaningful custom event instead.
# Identify user
Source: https://retain.so/docs/guides/identify
Register or update users in Retain
When a user signs up or updates their profile, send their data to Retain. You must identify a user before tracking events for them.
Call `/identify` before `/track`. Events can only be recorded for users that
have been identified.
## Identify a user
```typescript Node.js icon=square-js theme={"theme":"vesper"}
import { Retain } from '@retain-so/sdk';
const retain = new Retain(process.env.RETAIN_WRITE_KEY);
retain.identify({
userId: 'user_123',
email: 'jane@example.com',
properties: {
name: 'Jane Doe',
avatar: 'https://example.com/avatar.jpg',
// Add anything else about the user here
},
});
```
```python Python icon=python theme={"theme":"vesper"}
import os
import requests
requests.post(
'https://api.retain.so/identify',
headers={
'Content-Type': 'application/json',
'Authorization': f'Basic {os.environ["RETAIN_WRITE_KEY"]}',
},
json={
'userId': 'user_123',
'email': 'jane@example.com',
'properties': {
'name': 'Jane Doe',
'avatar': 'https://example.com/avatar.jpg',
# Add anything else about the user here
},
},
)
```
```php PHP icon=php theme={"theme":"vesper"}
$payload = json_encode([
'userId' => 'user_123',
'email' => 'jane@example.com',
'properties' => [
'name' => 'Jane Doe',
'avatar' => 'https://example.com/avatar.jpg',
],
]);
$ch = curl_init('https://api.retain.so/identify');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'Authorization: Basic ' . getenv('RETAIN_WRITE_KEY'),
],
CURLOPT_POSTFIELDS => $payload,
]);
curl_exec($ch);
curl_close($ch);
```
```ruby Ruby icon=gem theme={"theme":"vesper"}
require 'net/http'
require 'json'
uri = URI('https://api.retain.so/identify')
req = Net::HTTP::Post.new(uri)
req['Content-Type'] = 'application/json'
req['Authorization'] = "Basic #{ENV.fetch('RETAIN_WRITE_KEY')}"
req.body = {
userId: 'user_123',
email: 'jane@example.com',
properties: {
name: 'Jane Doe',
avatar: 'https://example.com/avatar.jpg',
# Add anything else about the user here
},
}.to_json
Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) { |http| http.request(req) }
```
```java Java icon=java theme={"theme":"vesper"}
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
String json = """
{
"userId": "user_123",
"email": "jane@example.com",
"properties": {
"name": "Jane Doe",
"avatar": "https://example.com/avatar.jpg"
}
}
""";
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://api.retain.so/identify"))
.header("Content-Type", "application/json")
.header("Authorization", "Basic " + System.getenv("RETAIN_WRITE_KEY"))
.POST(HttpRequest.BodyPublishers.ofString(json))
.build();
HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());
```
```bash cURL icon=globe theme={"theme":"vesper"}
curl -X POST https://api.retain.so/identify \
-H "Content-Type: application/json" \
-H "Authorization: Basic $RETAIN_WRITE_KEY" \
-d '{
"userId": "user_123",
"email": "jane@example.com",
"properties": {
"name": "Jane Doe",
"avatar": "https://example.com/avatar.jpg"
}
}'
```
## Identify a user with account
For products with workspaces or teams, you can associate users with an account and mark the account owner:
```typescript Node.js icon=square-js theme={"theme":"vesper"}
import { Retain } from '@retain-so/sdk';
const retain = new Retain(process.env.RETAIN_WRITE_KEY);
retain.identify({
userId: 'user_123',
email: 'jane@example.com',
isAccountOwner: true,
account: {
id: 'acct_456',
name: 'Acme Inc',
avatar: 'https://example.com/acme-logo.png',
},
properties: {
name: 'Jane Doe',
avatar: 'https://example.com/avatar.jpg',
},
});
```
```python Python icon=python theme={"theme":"vesper"}
import os
import requests
requests.post(
'https://api.retain.so/identify',
headers={
'Content-Type': 'application/json',
'Authorization': f'Basic {os.environ["RETAIN_WRITE_KEY"]}',
},
json={
'userId': 'user_123',
'email': 'jane@example.com',
'isAccountOwner': True,
'account': {
'id': 'acct_456',
'name': 'Acme Inc',
'avatar': 'https://example.com/acme-logo.png',
},
'properties': {
'name': 'Jane Doe',
'avatar': 'https://example.com/avatar.jpg',
},
},
)
```
```php PHP icon=php theme={"theme":"vesper"}
$payload = json_encode([
'userId' => 'user_123',
'email' => 'jane@example.com',
'isAccountOwner' => true,
'account' => [
'id' => 'acct_456',
'name' => 'Acme Inc',
'avatar' => 'https://example.com/acme-logo.png',
],
'properties' => [
'name' => 'Jane Doe',
'avatar' => 'https://example.com/avatar.jpg',
],
]);
$ch = curl_init('https://api.retain.so/identify');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'Authorization: Basic ' . getenv('RETAIN_WRITE_KEY'),
],
CURLOPT_POSTFIELDS => $payload,
]);
curl_exec($ch);
curl_close($ch);
```
```ruby Ruby icon=gem theme={"theme":"vesper"}
require 'net/http'
require 'json'
uri = URI('https://api.retain.so/identify')
req = Net::HTTP::Post.new(uri)
req['Content-Type'] = 'application/json'
req['Authorization'] = "Basic #{ENV.fetch('RETAIN_WRITE_KEY')}"
req.body = {
userId: 'user_123',
email: 'jane@example.com',
isAccountOwner: true,
account: {
id: 'acct_456',
name: 'Acme Inc',
avatar: 'https://example.com/acme-logo.png',
},
properties: {
name: 'Jane Doe',
avatar: 'https://example.com/avatar.jpg',
},
}.to_json
Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) { |http| http.request(req) }
```
```java Java icon=java theme={"theme":"vesper"}
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
String json = """
{
"userId": "user_123",
"email": "jane@example.com",
"isAccountOwner": true,
"account": {
"id": "acct_456",
"name": "Acme Inc",
"avatar": "https://example.com/acme-logo.png"
},
"properties": {
"name": "Jane Doe",
"avatar": "https://example.com/avatar.jpg"
}
}
""";
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://api.retain.so/identify"))
.header("Content-Type", "application/json")
.header("Authorization", "Basic " + System.getenv("RETAIN_WRITE_KEY"))
.POST(HttpRequest.BodyPublishers.ofString(json))
.build();
HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());
```
```bash cURL theme={"theme":"vesper"}
curl -X POST https://api.retain.so/identify \
-H "Content-Type: application/json" \
-H "Authorization: Basic $RETAIN_WRITE_KEY" \
-d '{
"userId": "user_123",
"email": "jane@example.com",
"isAccountOwner": true,
"account": {
"id": "acct_456",
"name": "Acme Inc",
"avatar": "https://example.com/acme-logo.png"
},
"properties": {
"name": "Jane Doe",
"avatar": "https://example.com/avatar.jpg"
}
}'
```
See [POST /identify](/docs/api-reference/identify/identify-a-user) in the API Reference for more details.
## Reserved traits
Everything you send in `properties` is stored as a trait on the customer. A few keys are reserved and power specific features in the dashboard:
| Key | Type | What it powers |
| - | - | - |
| `name` | string | Display name shown across the dashboard |
| `avatar` | string (URL) | Customer avatar shown across the dashboard |
| `plan` | string | Retention cohorts split by pricing plan (e.g. `starter`, `pro`) |
| `acquisitionChannel` | string | Retention cohorts split by where the customer came from (e.g. `organic`, `referral`) |
| `companySize` | string | Retention cohorts split by company size bucket (e.g. `1-10`, `11-50`) |
| `segment` | string | Retention cohorts split by the company's ICP segment (e.g. `agency`, `creator`) |
The `segment` trait is the segment your customer belongs to in your ICP. It
is not the stage Retain gives the account in the [journey](/docs/journey)
(Not activated, Activated, Basic, Advanced, Power). Stages are computed from
usage, not sent by you.
Any other key is stored as a custom trait. Custom traits with a small set of values (20 or fewer) also show up as cohort grouping options in the Metrics page.
### Traits are merged, not replaced
Each `identify` call does a shallow merge: keys you send overwrite the same keys, keys you omit are preserved. You can send `plan` on signup and `acquisitionChannel` later without losing anything. Send `null` for a key to clear it.
### Split retention cohorts by trait
Send the cohort traits and the Metrics page lets you split the retention chart by any of them. That is how you find out which plan, channel, or segment quietly churns the most:
```typescript Node.js icon=square-js theme={"theme":"vesper"}
retain.identify({
userId: 'user_123',
email: 'jane@example.com',
properties: {
plan: 'starter',
acquisitionChannel: 'organic',
companySize: '11-50',
segment: 'agency',
},
});
```
```bash cURL theme={"theme":"vesper"}
curl -X POST https://api.retain.so/identify \
-H "Content-Type: application/json" \
-H "Authorization: Basic $RETAIN_WRITE_KEY" \
-d '{
"userId": "user_123",
"email": "jane@example.com",
"properties": {
"plan": "starter",
"acquisitionChannel": "organic",
"companySize": "11-50",
"segment": "agency"
}
}'
```
## Next steps
Record events for identified users.
# Installation
Source: https://retain.so/docs/guides/installation
Pick your integration method and start sending events in minutes.
There are three ways to get events into Retain, and you only need one of them.
Use the **Node.js SDK** if you are on Node. Use the **HTTP API** from any other language, with nothing to install. Or, if you already track product usage in a tool like PostHog, **connect that tool** and skip instrumentation entirely.
## Node.js
Install the SDK with your preferred package manager.
**Requirements:** Node.js 20 or later.
```bash npm theme={"theme":"vesper"}
npm install @retain-so/sdk
```
```bash pnpm theme={"theme":"vesper"}
pnpm add @retain-so/sdk
```
```bash yarn theme={"theme":"vesper"}
yarn add @retain-so/sdk
```
```bash bun theme={"theme":"vesper"}
bun add @retain-so/sdk
```
Continue the Quickstart with [Authentication](/docs/guides/authentication), then [Identify](/docs/guides/identify) and [Track](/docs/guides/track).
## Other languages
You don’t need to install anything
Just grab your Project Token in [Authentication](/docs/guides/authentication) then move on to [Identify](/docs/guides/identify) and [Track](/docs/guides/track) for HTTP examples in your language.
If you need more details, check the [API reference](/docs/api-reference/introduction).
Official SDKs for other languages are coming soon.
## Already tracking with a product analytics tool
If your product events already flow into PostHog, you do not need to instrument anything a second time. Point a PostHog realtime destination at Retain and the events you already collect start arriving, usually in a couple of minutes.
See [Connect PostHog](/docs/guides/connect-posthog) for the full setup.
Mixpanel and Amplitude are coming soon.
## Next steps
Get your Project Token and use it from the SDK or HTTP client.
Forward the events you already track, no re-instrumentation needed.
Register users in Retain before tracking events.
Record events as they happen in your product.
# Track events
Source: https://retain.so/docs/guides/track
Record events for users in Retain
After identifying a user, track events as they happen in your product.
The user must have been identified first using the
[Identify](/docs/guides/identify) endpoint.
## Creating and configuring events
You can start sending events immediately using `track`.
If the event does not exist yet, **Retain will automatically create it for you.**
This makes it easy to start tracking quickly and refine the configuration later.
After the event appears in the Events page, you only need to configure:
* **Importance**\
Defines how critical this event is for your product. Retain uses this information when calculating customer health and identifying churn risk. High-importance events typically represent moments where users extract significant value from your product.
* **Expected frequency**\
Indicates how often you expect this event to happen. This helps Retain understand normal usage patterns and detect when an account’s activity drops below expected levels.
## Tracking events
```typescript Node.js icon=square-js theme={"theme":"vesper"}
import { Retain } from '@retain-so/sdk';
const retain = new Retain(process.env.RETAIN_WRITE_KEY);
retain.track({
userId: 'user_123',
event: 'report_exported',
properties: {
format: 'csv',
// Add anything else about the event here
},
});
```
```python Python icon=python theme={"theme":"vesper"}
import os
import requests
requests.post(
'https://api.retain.so/track',
headers={
'Content-Type': 'application/json',
'Authorization': f'Basic {os.environ["RETAIN_WRITE_KEY"]}',
},
json={
'userId': 'user_123',
'event': 'report_exported',
'properties': {
'format': 'csv',
# Add anything else about the event here
},
},
)
```
```php PHP icon=php theme={"theme":"vesper"}
$payload = json_encode([
'userId' => 'user_123',
'event' => 'report_exported',
'properties' => [
'format' => 'csv',
// Add anything else about the event here
],
]);
$ch = curl_init('https://api.retain.so/track');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'Authorization: Basic ' . getenv('RETAIN_WRITE_KEY'),
],
CURLOPT_POSTFIELDS => $payload,
]);
curl_exec($ch);
curl_close($ch);
```
```ruby Ruby icon=gem theme={"theme":"vesper"}
require 'net/http'
require 'json'
uri = URI('https://api.retain.so/track')
req = Net::HTTP::Post.new(uri)
req['Content-Type'] = 'application/json'
req['Authorization'] = "Basic #{ENV.fetch('RETAIN_WRITE_KEY')}"
req.body = {
userId: 'user_123',
event: 'report_exported',
properties: {
format: 'csv',
# Add anything else about the event here
},
}.to_json
Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) { |http| http.request(req) }
```
```java Java icon=java theme={"theme":"vesper"}
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
// Add anything else about the event inside "properties"
String json = """
{
"userId": "user_123",
"event": "report_exported",
"properties": { "format": "csv" }
}
""";
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://api.retain.so/track"))
.header("Content-Type", "application/json")
.header("Authorization", "Basic " + System.getenv("RETAIN_WRITE_KEY"))
.POST(HttpRequest.BodyPublishers.ofString(json))
.build();
HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());
```
```bash cURL theme={"theme":"vesper"}
# Add anything else about the event inside "properties"
curl -X POST https://api.retain.so/track \
-H "Content-Type: application/json" \
-H "Authorization: Basic $RETAIN_WRITE_KEY" \
-d '{
"userId": "user_123",
"event": "report_exported",
"properties": { "format": "csv" }
}'
```
See [POST /track](/docs/api-reference/track/track-an-event) in the API Reference for more details.
That’s it. You’re now tracking events with Retain. Nice, now the fun part begins.
# Start here
Source: https://retain.so/docs/index
Retain helps you understand your customers through events and revenue data.
## Core concepts
### Events
Events represent meaningful user actions that happen inside your product. Moments where users actually extract **value** from it, such as creating a project, scheduling an appointment, or sending an invoice.
**Examples**: on Airbnb, booking a house is a meaningful event. On YouTube, it’s watching a video. On Spotify, it’s listening to a song. You get the idea.
### Users
Users are the people using your product. Each user has a unique ID that lets you follow their journey over time and understand their behavior.
### Accounts
Accounts are the organizations your users belong to. Essential for B2B products where behavior depends on company context.
### Revenue (via payment providers)
By connecting your payment provider, Retain automatically tracks billing events like subscriptions, renewals, upgrades, and cancellations, which combined with product usage data help you understand user behavior across the entire lifecycle.
## Next steps
Use our SDK, a plain HTTP call, or forward events from a tool you already
run like PostHog.
Sync your customers, MRR and churn metrics automatically.
# Journey
Source: https://retain.so/docs/journey
See how far each account got into your product, and which ones are at risk.
The journey shows how far into your product every account got. That answer is its **stage**.
Each stage shows how many accounts are in it and how much MRR they bring. Pick a stage to list its accounts with their churn risk (Healthy, Stable, High, Critical), the same risk you see on Customers and in alerts. Accounts still in onboarding or activation have no churn risk yet and show as **Not scored yet**.
Churned accounts, where every subscription has ended, are left out of the journey. If one subscribes again, it comes back in the stage it had.
## The stages
Every account starts as Not activated and moves toward Power. Each stage is a level of product usage.
| Stage | What it means | Default rule |
| - | - | - |
| Not activated | Signed up, hasn't felt the value yet | Where every account starts |
| Activated | Got first value | Did your activation event in the first 7 or 14 days or, after the first 14 days, reaches Basic |
| Basic | Uses the essentials | At least 1 key feature event in the last 28 days |
| Advanced | Uses it with breadth | Used at least as many distinct key features in 28 days as the median active account (minimum 2) |
| Power | Depends on the product | Meets the Advanced rule and ranks in the top 25% of active accounts by intensity |
All calculations use a rolling 28-day window. Four full weeks, so no day of the week gets to bias the result.
Key features are the events you mark as key features in Retain. An active
account is one with at least 1 event in the last 28 days and a subscription
that hasn't been canceled.
Intensity is `active days × ln(1 + key events)` over 28 days. Active days weigh more than raw volume, so a script firing 1,000 events in one afternoon doesn't crown itself a power user.
### Moving between stages
Accounts go up the moment they meet a rule. They go down only after missing it for 7 days straight, so one quiet weekend doesn't send anyone backward.
Activation is permanent. Once an account has activated, it never drops back to Not activated.
## Stalled accounts
An account is also flagged **stalled** when it has sat in its stage longer than 75% of the accounts that have been in that stage (those who already left and those still there), with a minimum of 14 days. While there are fewer than 5 accounts to compare, the limit is 28 days. Power accounts and churned accounts are never stalled.
## How stages are defined
You don't write the rules. Retain derives them from your own data.
* **Activation event.** Retain looks at accounts that subscribed 60 or more days ago and finds the event that best separates the ones who stayed from the ones who left. It tries counts of 1, 2, 3, 5, and 10 inside the first 7 or 14 days. It needs at least 30 such accounts, and at least 10 on each side of the split.
* **Fallback.** With fewer than 30 accounts or no clear winner, activation is "1 key feature event within 14 days".
* **Basic, Advanced, Power.** Percentiles and medians across your active accounts, as shown in the table above.
* **What defines each stage.** For Advanced and Power, Retain lists up to 3 events that show up much more in that stage than in the one below it (at least 2x as often, in at least 30% of its accounts).
Each stage carries a confidence level. High means at least 30 accounts and retention at least 10 points above the previous stage. Medium means at least 15 accounts. Anything else, and every fallback, is low. Confidence is informative and never blocks a classification.
### Editing the rules
You can replace the rules for Activated, Basic, Advanced, or Power with your own, up to 3 rules per stage, all of which must be met. A manual definition is never overwritten by the daily job.
Retain keeps refreshing its stats and the events that define the stage. Only the rules stay yours. To go back, use **Reset to automatic** on that stage.
## Day one: bringing your history
A journey with no history starts empty. There are two ways to fill it, and you can use both.
### Import from PostHog
If you use PostHog, Retain can import the last 90 days of events.
In PostHog, open your user settings and create a personal API key. Give
it the **Query Read** scope.
It's the number in your PostHog project settings.
Go to **Sources → PostHog**, then **Import the last 90 days**. Pick your
region (US, EU, or self-hosted). For self-hosted, enter your public
`https://` URL. Add the Project ID and the key.
The import stops at 2,000,000 events, and Retain marks it as capped when that happens. For realtime events going forward, see [Connect PostHog](/docs/guides/connect-posthog).
### Send history through the API
Without PostHog, send past events with a `timestamp`. The `/track` endpoint accepts an ISO 8601 date, so the event lands where it happened instead of today.
```bash cURL theme={"theme":"vesper"}
curl -X POST https://api.retain.so/track \
-H "Content-Type: application/json" \
-H "Authorization: Basic $RETAIN_WRITE_KEY" \
-d '{
"userId": "user_123",
"event": "report_exported",
"timestamp": "2026-08-14T09:30:00Z"
}'
```
The `track` method of `@retain-so/sdk` doesn't take a `timestamp` yet. Use
the HTTP endpoint above for backfills.
After a PostHog import, Retain replays the last 90 days, so the journey shows where accounts have been and not only where they are now. History you send through `/track` shows up on the next daily run.
Without any history, the journey still works. It fills in as events arrive.
## When it updates
Journey states are recomputed once a day, at 09:30 UTC. Stages and the rules Retain derives all refresh in that run.
# What should I track?
Source: https://retain.so/docs/plan
To measure retention and detect churn risk, Retain needs to understand how users interact with your product. This is done by tracking the meaningful actions they perform.
## Start with a small set of events
When implementing event tracking for the first time, it’s tempting to track everything. In practice, it’s much more effective to begin with a small number of **high-value** events.
A good starting point is **3-5 events** that represent moments where users actually get value from your product.
Focus on actions that indicate meaningful product usage rather than simple page visits or passive interactions.
Events related to **onboarding and user activation are especially important**, particularly if your product offers a **free trial**, since they help identify whether users are reaching the first moments of value.
Most churn happens at the beginning of the user journey, so tracking these
early moments is critical to understand whether users are successfully getting
started with your product.
**Examples might include:**
* Creating a project
* Scheduling an appointment
* Sending an invoice
* Completing a workflow
* Inviting a teammate
When you create your organization in Retain, we automatically scan your
product’s landing page and suggest a few key events based on the value your
product provides. See the "Suggested Events" on the
[events](https://retain.so/dashboard/events) page.
When naming events, keep them short and easy to understand. A simple convention that works well is: **Object + Action (past tense).**
**Examples:**
* project\_created
* appointment\_scheduled
* invoice\_sent
* teammate\_invited
## Prefer server-side tracking
We recommend sending events from your backend rather than directly from the client.
Server-side tracking is generally more reliable and secure, since it prevents exposing sensitive information such as API keys and reduces the risk of events being manipulated or sent incorrectly from the client.
It also ensures that the data being sent to Retain reflects what actually happened in your system, since events are generated directly from your application’s business logic.
## Next steps
Alright, let’s stop talking and start tracking.
Send events with our SDK or a plain HTTP call.
Already tracking these events elsewhere? Forward them instead.