01Implementation Scope
This section defines the implementation baseline. Resolve every item marked pending before starting the dependent implementation step.
Scope decisions to record
This guide is a reusable template. Replace every bracketed placeholder with the project's decision before implementation starts, and keep this table as the single record of scope.
| Scope item | Decision | Status |
|---|---|---|
| Adjust SDK in the mobile app (installs, sessions, attribution) | Prerequisite — covered by the platform guide | Baseline |
| Backend-confirmed purchase / payment events via S2S | In scope — taxonomy pending | Confirm taxonomy |
| Refunds / chargebacks | [Required?] | Pending |
| Subscription renewals / cancellations | [Required? Via S2S or Adjust Subscriptions?] | Pending |
| Other server-side milestones (e.g. KYC approved, loan disbursed, order delivered) | [Inventory required] | Pending |
| S2S Security token enforcement | Required for production | Baseline |
| Data residency region | [Default / EU / US / TR / KSA] | Pending |
| Raw data export / real-time callbacks | [Decide before launch — not retrospective] | Time-critical |
02Target Architecture
All Adjust calls are isolated in one NestJS module. Domain services record an event intent in an outbox table inside their own database transaction; a worker delivers it to Adjust. Nothing else in the codebase calls Adjust directly.
Components
| Component | Responsibility |
|---|---|
AdjustModule | Owns configuration, the HTTP client, the event catalog and the worker. The only place that knows Adjust exists. |
AdjustDeviceContextService | Stores the Adjust identifiers the app reports for each user and device (§6). |
AdjustTracker | Public facade for domain code: track(eventKey, payload, tx) writes one outbox row in the caller's transaction (§9). |
AdjustOutboxWorker | Claims pending rows, preserves per-device ordering, retries transient failures (§10). |
AdjustS2sClient | Builds the form-encoded request, adds the Bearer token, classifies the response (§8). |
Design principles
- Fire only on confirmed state. An event is recorded when the backend's own state changes (payment captured, order delivered) — never on a client request that might still fail.
- Never call Adjust inside the request path. A slow or failing Adjust call must not slow down or fail a checkout. The outbox decouples them.
- Idempotency is the sender's job. The S2S endpoint does not deduplicate retried requests; a unique dedupe key on the outbox row does.
- One source per event. If the backend sends an event, the app must not send the same event through the SDK.
03Prerequisites
Collect these before writing code. Most S2S problems in production trace back to a missing item from this list.
- Adjust SDK live in the app and recording sessions in the target environment.
- App token for every Adjust app the backend sends events for.
- Event tokens created for every backend-owned event (§4).
- S2S Security token with the Events scope.
- Mobile team agreed to report device identifiers to the backend (§6).
- Secrets manager or encrypted environment configuration for the S2S token.
- Outbound HTTPS from the backend to the Adjust S2S host allowed by firewall / egress rules.
- Server clocks synchronised (NTP) — event timestamps are sent as Unix time.
- Queue infrastructure decided: database outbox with a scheduler, or BullMQ with Redis.
- Test devices registered in the Adjust Testing Console.
Information to collect
| Item | Source | Used in |
|---|---|---|
| App token(s) | Adjust dashboard → AppView → app | Every request (app_token) |
| Event tokens | Adjust dashboard → app → event settings | Event catalog (§9) |
| S2S Security token | Adjust dashboard → app → Protection → S2S Security | Authorization header (§14) |
| Data residency status | Adjust dashboard → app → Protection tab / Adjust account team | S2S base URL (§15) |
| Payment provider / store webhook formats | Backend team | Revenue mapping (§11) |
04Adjust Dashboard Setup
Configure the dashboard before the backend sends its first request. Tokens created here are referenced by the backend configuration.
Create the backend-owned event tokens
In the app's event settings, create one event per backend-owned action from the signed-off taxonomy. A naming prefix such as s2s_ (for example s2s_purchase) keeps backend events distinguishable from SDK events in reports.
Decide per event whether it is unique (counted once per device, e.g. s2s_first_purchase). Repeated unique events are rejected by Adjust with a 400 response — the worker treats that as expected, not as a failure (§13).
Create the S2S Security token
Go to AppView → All apps → [app] → Protection → S2S Security → Open S2S Security → + New token. Name the token after the service (e.g. nestjs-backend-prod), select the Events scope, add it and copy it straight into the secrets manager.
Do not switch on Enable S2S authentication yet. Enforcement is turned on only after the backend has been verified to send the token on every request (§18).
Link events to media partners
For every partner that should receive backend events, map the S2S event tokens in the partner module. If an SDK event is being moved to S2S, link the new S2S event before the SDK event is removed from the app (§5).
Register test devices
Add the QA devices to the Testing Console. It shows each device's adid, attribution and the events Adjust received for it — the fastest way to confirm that a backend event reached the right device.
environment request parameter decides where the event lands. Adjust defaults to production when the parameter is missing, so the backend must always send it explicitly (§7).
05SDK vs S2S Ownership
Decide, event by event, whether the app or the backend sends it. The rule of thumb: behavioural and funnel events stay on the SDK; events the backend confirms — or that happen while the app is closed — go through S2S.
| Signal | Owner | Reason |
|---|---|---|
| Install, session, reattribution | SDK (automatic) | Recorded by the SDK on app start. Never sent as events, never sent from the backend. |
| Screen views, add to cart, login, registration started | SDK | Happen in the app; no server confirmation needed. |
| Registration completed / KYC approved | [SDK or S2S] | S2S if approval happens on the server after the user has left the screen. |
| Purchase / payment confirmed | S2S | Amount and status come from the payment provider; harder to spoof than a client-side event. |
| Refund, chargeback | S2S | Happens on the server, often days later, while the app may not be running. |
| Subscription renewal / cancellation | S2S or Adjust Subscriptions | Triggered by store server notifications. Choose one route (§11). |
Moving an existing SDK event to S2S
If the app already sends the event through the SDK, follow Adjust's transition order so that nothing is double-counted or lost during the switch:
- Create a new S2S event token that mirrors the SDK event (e.g.
s2s_purchasenext topurchase). - Send the same callback and partner parameter names and values as the SDK event.
- Deploy the backend event and compare its counts with the SDK event in BI until they match.
- Switch BI reporting to the S2S event, then link it to every partner that received the SDK event.
- Release an app update that removes the SDK event, and hide the old SDK token in the dashboard once traffic on it stops.
06Device Context from the App
An S2S event has to name a device Adjust already knows from the SDK. The backend cannot create these identifiers — the app must read them from the Adjust SDK and report them.
Identifiers to report
| Identifier | Platform | Notes |
|---|---|---|
adid | iOS + Android | Adjust's own device ID, generated by the SDK. Available whatever the user's ad-tracking choice. Send it on every event. |
idfa | iOS | Only exists when the user authorised tracking (ATT). Send when present. |
idfv | iOS | Backup identifier. |
gps_adid | Android | Google advertising ID. When the user opted out of ads personalisation, the SDK returns zeros — do not store or send an all-zero value. |
| Platform, app version | Both | Platform selects the app and event tokens; app version helps debugging. |
adid and the advertising ID together. Adjust's S2S event reference lists the advertising ID (idfa / gps_adid) as the identifier parameter and adid as recommended. Because the advertising ID is missing for ATT-denied or opted-out users, sending adid plus every available ID keeps those users measurable.
Reading the identifiers in the app (SDK v5)
All getters are asynchronous. Call them after initSdk; a null adid means the SDK has not finished its first session yet — retry on the next app start instead of blocking the UI.
| Platform | adid | Advertising / vendor ID |
|---|---|---|
| Android (Kotlin / Java) | Adjust.getAdid(listener) | Adjust.getGoogleAdId(context, listener) |
| iOS (Swift) | Adjust.adid { adid in } | Adjust.idfa { } · Adjust.idfv { } |
| Flutter / React Native / Unity | Use the equivalent getters of the plugin — see the platform implementation guide. | |
Backend endpoint
The app reports the identifiers on every app start once adid is available, and again right after login so the backend can link the device to the user. The backend upserts one row per user and adid.
// adjust/dto/adjust-device-context.dto.ts
import { IsBoolean, IsIn, IsOptional, IsString, IsUUID, Matches } from 'class-validator';
export class AdjustDeviceContextDto {
@IsIn(['ios', 'android'])
platform!: 'ios' | 'android';
@Matches(/^[a-f0-9]{32}$/i) // adid is a 32-character hex string
adid!: string;
@IsOptional() @IsUUID() idfa?: string;
@IsOptional() @IsUUID() idfv?: string;
@IsOptional() @IsUUID() gpsAdid?: string;
@IsOptional() @IsString() appVersion?: string;
@IsBoolean() measurementConsent!: boolean; // §15
}
// adjust/adjust-device-context.controller.ts
@Controller('v1/adjust/device-context')
@UseGuards(AuthGuard) // the app's existing auth guard
export class AdjustDeviceContextController {
constructor(private readonly contexts: AdjustDeviceContextService) {}
@Put()
@HttpCode(204)
async upsert(@Req() req: AuthedRequest, @Body() dto: AdjustDeviceContextDto) {
await this.contexts.upsert(req.user.id, dto, clientIpv4(req));
}
}
-- PostgreSQL. One row per user + Adjust device.
CREATE TABLE adjust_device_context (
user_id uuid NOT NULL,
adid char(32) NOT NULL,
platform text NOT NULL CHECK (platform IN ('ios','android')),
idfa uuid,
idfv uuid,
gps_adid uuid,
app_version text,
measurement_consent boolean NOT NULL,
last_ip_v4 inet,
last_seen_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (user_id, adid)
);
CREATE INDEX ON adjust_device_context (user_id, last_seen_at DESC);
07NestJS Module Setup
Create one feature module that owns everything Adjust-related. The examples target NestJS 12 and use TypeORM's EntityManager for SQL; the same structure works with Prisma or MikroORM.
Dependencies
npm i @nestjs/config@^12 @nestjs/schedule@^12 class-validator class-transformer joi@^18
# only if BullMQ is chosen instead of the database outbox (§10)
npm i @nestjs/bullmq@^12 bullmq
No HTTP client package is needed: Node.js ships fetch and AbortSignal.timeout.
require(esm), while ESM projects ("type": "module") need explicit .js extensions in relative imports — the examples below already use them. Joi schemas require Joi 18 or later; validationSchema also accepts any Standard Schema such as Zod or Valibot.
Module layout
src/adjust/
adjust.module.ts
adjust.config.ts # typed, validated configuration
adjust-event-catalog.ts # event keys → tokens (§9)
adjust-s2s.client.ts # HTTP call + response classification (§8, §13)
adjust.tracker.ts # facade used by domain code (§9)
adjust-outbox.worker.ts # delivery, retries, ordering (§10)
adjust-device-context.service.ts # identifiers reported by the app (§6)
adjust-device-context.controller.ts
dto/adjust-device-context.dto.ts
Configuration
// adjust/adjust.config.ts
import { type ConfigType, registerAs } from '@nestjs/config';
export const adjustConfig = registerAs('adjust', () => ({
enabled: process.env.ADJUST_S2S_ENABLED === 'true',
environment: process.env.ADJUST_ENVIRONMENT as 'sandbox' | 'production',
baseUrl: process.env.ADJUST_S2S_BASE_URL ?? 'https://s2s.adjust.com',
s2sToken: process.env.ADJUST_S2S_TOKEN ?? '',
appTokens: {
ios: process.env.ADJUST_APP_TOKEN_IOS ?? '',
android: process.env.ADJUST_APP_TOKEN_ANDROID ?? '',
},
timeoutMs: Number(process.env.ADJUST_HTTP_TIMEOUT_MS ?? 10000),
}));
export type AdjustConfig = ConfigType<typeof adjustConfig>;
// app.module.ts — fail fast on missing or wrong values (Joi 18+)
import Joi from 'joi';
ConfigModule.forRoot({
isGlobal: true,
load: [adjustConfig],
validationSchema: Joi.object({
ADJUST_S2S_ENABLED: Joi.boolean().default(false),
ADJUST_ENVIRONMENT: Joi.string().valid('sandbox', 'production').required(),
ADJUST_S2S_BASE_URL: Joi.string().uri({ scheme: ['https'] }).default('https://s2s.adjust.com'),
ADJUST_S2S_TOKEN: Joi.string().when('ADJUST_S2S_ENABLED', { is: true, then: Joi.required() }),
ADJUST_APP_TOKEN_IOS: Joi.string().allow(''),
ADJUST_APP_TOKEN_ANDROID: Joi.string().allow(''),
ADJUST_HTTP_TIMEOUT_MS: Joi.number().integer().min(1000).default(10000),
}),
}),
| Variable | Staging | Production |
|---|---|---|
ADJUST_S2S_ENABLED | false → true after shadow mode | false → true at go-live |
ADJUST_ENVIRONMENT | sandbox | production |
ADJUST_S2S_BASE_URL | https://s2s.adjust.com, or the regional host if data residency is active (§15) | |
ADJUST_S2S_TOKEN | From the secrets manager — never committed, never logged | |
Module
// adjust/adjust.module.ts
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { adjustConfig } from './adjust.config.js';
import { AdjustS2sClient } from './adjust-s2s.client.js';
import { AdjustTracker } from './adjust.tracker.js';
import { AdjustOutboxWorker } from './adjust-outbox.worker.js';
import { AdjustDeviceContextService } from './adjust-device-context.service.js';
import { AdjustDeviceContextController } from './adjust-device-context.controller.js';
@Module({
imports: [ConfigModule.forFeature(adjustConfig)],
controllers: [AdjustDeviceContextController],
providers: [
AdjustS2sClient,
AdjustTracker,
AdjustOutboxWorker,
AdjustDeviceContextService,
],
exports: [AdjustTracker, AdjustDeviceContextService],
})
export class AdjustModule {}
// app.module.ts
@Module({ imports: [ScheduleModule.forRoot(), AdjustModule /* , ... */] })
export class AppModule {}
production. The environment parameter defaults to production on Adjust's side. A staging server that forgets the variable writes test purchases into live reports, partner postbacks and revenue — and they cannot be deleted afterwards. The Joi schema above makes the variable mandatory.
08S2S Client Service
One injectable class builds the request, sends it and classifies the result. It has no knowledge of orders or users — only of Adjust's request format.
// adjust/adjust-s2s.client.ts
import { Inject, Injectable } from '@nestjs/common';
import { adjustConfig, type AdjustConfig } from './adjust.config.js';
export interface S2sEventRequest {
appToken: string;
eventToken: string;
adid: string;
idfa?: string;
idfv?: string;
gpsAdid?: string;
createdAtUnix: number; // seconds, time the business event happened
revenue?: { amount: string; currency: string }; // major units, e.g. "149.99" + "SAR"
callbackParams?: Record<string, string>; // flat, string values only
partnerParams?: Record<string, string>;
ipAddress?: string; // IPv4 of the user's device, if known
}
export type S2sResult =
| { kind: 'ok' }
| { kind: 'retry'; status: number; body: string }
| { kind: 'drop'; status: number; body: string; reason: string }
| { kind: 'alert'; status: number; body: string };
@Injectable()
export class AdjustS2sClient {
constructor(@Inject(adjustConfig.KEY) private readonly cfg: AdjustConfig) {}
async sendEvent(e: S2sEventRequest): Promise<S2sResult> {
const form = new URLSearchParams({
s2s: '1',
app_token: e.appToken,
event_token: e.eventToken,
adid: e.adid,
created_at_unix: String(e.createdAtUnix),
environment: this.cfg.environment, // always explicit — Adjust defaults to production
});
if (e.idfa) form.set('idfa', e.idfa);
if (e.idfv) form.set('idfv', e.idfv);
if (e.gpsAdid) form.set('gps_adid', e.gpsAdid);
if (e.ipAddress) form.set('ip_address', e.ipAddress);
if (e.revenue) {
form.set('revenue', e.revenue.amount);
form.set('currency', e.revenue.currency);
}
if (e.callbackParams) form.set('callback_params', JSON.stringify(e.callbackParams));
if (e.partnerParams) form.set('partner_params', JSON.stringify(e.partnerParams));
let res: Response;
try {
res = await fetch(`${this.cfg.baseUrl}/event`, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Authorization: `Bearer ${this.cfg.s2sToken}`,
},
body: form, // URLSearchParams is URL-encoded by fetch
signal: AbortSignal.timeout(this.cfg.timeoutMs),
});
} catch (err) {
return { kind: 'retry', status: 0, body: String(err) }; // network error or timeout
}
return classifyS2sResponse(res.status, await res.text()); // §13
}
}
callback_params and partner_params must be a flat JSON object with string values — no nesting, no numbers or booleans. URLSearchParams handles the URL-encoding; do not encode the JSON a second time.
09Event Catalog & Tracking
Event tokens live in one controlled file. Domain code refers to business event keys, never to raw tokens.
Tracking plan (template)
| Event key | Trigger (backend state change) | Adjust event | Revenue | Callback parameters |
|---|---|---|---|---|
purchase_confirmed | Payment captured by the provider (webhook verified) | s2s_purchase | Yes | order_id, payment_method |
refund_completed | Refund settled by the provider | s2s_refund | No (§11) | order_id, refund_amount, refund_currency |
subscription_renewed | Store server notification verified | s2s_renewal | Yes | subscription_id, product_id |
[kyc_approved] | [Back-office approval] | [s2s_kyc_approved] | No | [TBD] |
// adjust/adjust-event-catalog.ts — the single place where tokens live
type Platform = 'ios' | 'android';
interface AdjustEventDef {
name: string; // Adjust dashboard name, for logs only
revenue: boolean;
tokens: Record<Platform, string>; // same token twice if iOS and Android share one Adjust app
}
export const ADJUST_EVENTS = {
purchase_confirmed: { name: 's2s_purchase', revenue: true, tokens: { ios: '[token]', android: '[token]' } },
refund_completed: { name: 's2s_refund', revenue: false, tokens: { ios: '[token]', android: '[token]' } },
subscription_renewed: { name: 's2s_renewal', revenue: true, tokens: { ios: '[token]', android: '[token]' } },
} as const satisfies Record<string, AdjustEventDef>;
export type AdjustEventKey = keyof typeof ADJUST_EVENTS;
The tracker facade
track() takes the caller's transaction, so the outbox row is committed together with the business change — or not at all. If the caller does not know the device, the tracker resolves it from the device context (§6).
// adjust/adjust.tracker.ts
import { Injectable } from '@nestjs/common';
import type { EntityManager } from 'typeorm';
import type { AdjustEventKey } from './adjust-event-catalog.js';
import { AdjustDeviceContextService } from './adjust-device-context.service.js';
export interface TrackInput {
eventKey: AdjustEventKey;
dedupeKey: string; // stable business ID, e.g. `purchase:${providerPaymentId}`
userId: string;
adid?: string; // device that acted, if known
occurredAt: Date; // when the business event happened
revenue?: { amount: string; currency: string };
callbackParams?: Record<string, string>;
partnerParams?: Record<string, string>;
ipV4?: string;
}
@Injectable()
export class AdjustTracker {
constructor(private readonly contexts: AdjustDeviceContextService) {}
async track(tx: EntityManager, input: TrackInput): Promise<void> {
const device = await this.contexts.resolve(tx, input.userId, input.adid);
await tx.query(
`INSERT INTO adjust_outbox
(dedupe_key, event_key, user_id, adid, platform, occurred_at,
revenue_amount, revenue_currency, callback_params, partner_params, ip_v4, status)
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12)
ON CONFLICT (dedupe_key) DO NOTHING`,
[
input.dedupeKey, input.eventKey, input.userId,
device?.adid ?? null, device?.platform ?? null, input.occurredAt,
input.revenue?.amount ?? null, input.revenue?.currency ?? null,
input.callbackParams ?? null, input.partnerParams ?? null, input.ipV4 ?? null,
device ? 'pending' : 'no_device', // kept for monitoring, never sent
],
);
}
}
Calling it from domain code
// payments/payment-webhook.service.ts — after the provider's signature is verified
await this.dataSource.transaction(async (tx) => {
await tx.update(Order, order.id, { status: 'paid', paidAt: payment.capturedAt });
await this.adjust.track(tx, {
eventKey: 'purchase_confirmed',
dedupeKey: `purchase:${payment.providerPaymentId}`,
userId: order.userId,
adid: order.adid, // saved from the checkout request
occurredAt: payment.capturedAt,
revenue: { amount: toMajorUnits(payment.amountMinor, payment.currency), currency: payment.currency },
callbackParams: { order_id: order.id, payment_method: payment.method },
ipV4: order.checkoutIpV4,
});
});
ON CONFLICT DO NOTHING. Never use a random UUID or a timestamp as the dedupe key.
10Outbox, Retries & Ordering
The worker turns outbox rows into S2S requests. It has three jobs: deliver each row once, retry transient failures, and keep events for the same device in chronological order.
-- PostgreSQL
CREATE TABLE adjust_outbox (
id bigserial PRIMARY KEY,
dedupe_key text NOT NULL UNIQUE,
event_key text NOT NULL,
user_id uuid,
adid char(32),
platform text,
occurred_at timestamptz NOT NULL,
revenue_amount text, -- exact major-unit string, e.g. '149.99'
revenue_currency char(3),
callback_params jsonb,
partner_params jsonb,
ip_v4 inet,
status text NOT NULL DEFAULT 'pending',
-- pending | sent | dropped | failed | no_device | expired
attempts int NOT NULL DEFAULT 0,
next_attempt_at timestamptz NOT NULL DEFAULT now(),
last_http_status int,
last_response text,
sent_at timestamptz,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX adjust_outbox_due ON adjust_outbox (next_attempt_at) WHERE status = 'pending';
CREATE INDEX adjust_outbox_order ON adjust_outbox (adid, event_key, occurred_at) WHERE status = 'pending';
Why ordering matters
Adjust requires S2S events to arrive in chronological order per device and event token. An event whose timestamp is earlier than one already accepted for the same device and event token is rejected. Parallel workers, or a delayed retry overtaken by a newer row, cause exactly this. The claim query below therefore never picks a row while an older pending row exists for the same device and event.
// adjust/adjust-outbox.worker.ts
import { Inject, Injectable, Logger } from '@nestjs/common';
import { Cron, CronExpression } from '@nestjs/schedule';
import { DataSource } from 'typeorm';
import { adjustConfig, type AdjustConfig } from './adjust.config.js';
import { AdjustS2sClient } from './adjust-s2s.client.js';
import { AdjustDeviceContextService } from './adjust-device-context.service.js';
import { ADJUST_EVENTS, type AdjustEventKey } from './adjust-event-catalog.js';
const MAX_ATTEMPTS = 12;
const DEVICE_NOT_FOUND_ATTEMPTS = 4; // first session may still be processing
const MAX_AGE_DAYS = 55; // Adjust rejects events older than 58 days
@Injectable()
export class AdjustOutboxWorker {
private readonly logger = new Logger(AdjustOutboxWorker.name);
constructor(
@Inject(adjustConfig.KEY) private readonly cfg: AdjustConfig,
private readonly client: AdjustS2sClient,
private readonly contexts: AdjustDeviceContextService,
private readonly db: DataSource,
) {}
@Cron(CronExpression.EVERY_10_SECONDS)
async tick(): Promise<void> {
if (!this.cfg.enabled) return; // shadow mode: rows accumulate, nothing is sent
const rows = await this.claimBatch(100);
rows.sort((a, b) => a.occurred_at.getTime() - b.occurred_at.getTime());
for (const row of rows) await this.deliver(row);
}
/** Leases due rows; safe with several app instances (SKIP LOCKED). */
private claimBatch(limit: number): Promise<OutboxRow[]> {
return this.db.query(
`WITH due AS (
SELECT o.id FROM adjust_outbox o
WHERE o.status = 'pending' AND o.next_attempt_at <= now()
AND NOT EXISTS (
SELECT 1 FROM adjust_outbox older
WHERE older.status = 'pending'
AND older.adid = o.adid AND older.event_key = o.event_key
AND older.occurred_at < o.occurred_at)
ORDER BY o.occurred_at
LIMIT $1
FOR UPDATE SKIP LOCKED)
UPDATE adjust_outbox SET next_attempt_at = now() + interval '2 minutes'
WHERE id IN (SELECT id FROM due)
RETURNING *`,
[limit],
).then(([rows]) => rows); // TypeORM returns [rows, count] for UPDATE … RETURNING on PostgreSQL
}
private async deliver(row: OutboxRow): Promise<void> {
const ageDays = (Date.now() - row.occurred_at.getTime()) / 86_400_000;
if (ageDays > MAX_AGE_DAYS) return this.finish(row, 'expired', null, 'too old for Adjust');
const def = ADJUST_EVENTS[row.event_key as AdjustEventKey];
const platform = row.platform as 'ios' | 'android';
const ctx = await this.contexts.ids(row.user_id, row.adid); // idfa / idfv / gps_adid
const result = await this.client.sendEvent({
appToken: this.cfg.appTokens[platform],
eventToken: def.tokens[platform],
adid: row.adid,
...ctx,
createdAtUnix: Math.floor(row.occurred_at.getTime() / 1000),
revenue: row.revenue_amount ? { amount: row.revenue_amount, currency: row.revenue_currency } : undefined,
callbackParams: row.callback_params ?? undefined,
partnerParams: row.partner_params ?? undefined,
ipAddress: row.ip_v4 ?? undefined,
});
switch (result.kind) {
case 'ok': return this.finish(row, 'sent', 200, null);
case 'drop': return this.finish(row, 'dropped', result.status, result.body);
case 'alert':
this.logger.error(`Adjust S2S rejected ${def.name} (#${row.id}): ${result.status} ${result.body}`);
return this.finish(row, 'failed', result.status, result.body);
case 'retry': {
const attempts = row.attempts + 1;
const limit = result.status === 404 ? DEVICE_NOT_FOUND_ATTEMPTS : MAX_ATTEMPTS;
if (attempts >= limit) return this.finish(row, 'failed', result.status, result.body);
const delaySec = Math.min(30 * 2 ** attempts, 6 * 3600); // 1 min … 6 h
await this.db.query(
`UPDATE adjust_outbox SET attempts = $2, last_http_status = $3, last_response = $4,
next_attempt_at = now() + make_interval(secs => $5) WHERE id = $1`,
[row.id, attempts, result.status, result.body.slice(0, 2000), delaySec],
);
}
}
}
private async finish(row: OutboxRow, status: string, http: number | null, body: string | null) {
await this.db.query(
`UPDATE adjust_outbox SET status = $2, last_http_status = $3, last_response = $4,
sent_at = CASE WHEN $2 = 'sent' THEN now() END WHERE id = $1`,
[row.id, status, http, body?.slice(0, 2000) ?? null],
);
}
}
failed when a human has to act (wrong token, inactive app, repeated server errors). After the cause is fixed, set them back to pending with attempts = 0. Requeue in occurred_at order and before newer rows for the same device are sent — otherwise the chronological-order rule rejects them.
jobId. Two caveats: enqueueing after commit is not atomic (a crash between commit and enqueue loses the event), and concurrent workers break per-device ordering unless jobs for the same device are serialised. The database outbox avoids both, which is why it is the default here.
11Revenue, Refunds & Renewals
Revenue events are the main reason to use S2S. Their value depends on three things: the amount comes from the payment source, the currency is sent as transacted, and every money movement has exactly one event.
Amount and currency
- Take the amount from the provider's confirmation (webhook or API), never from the app's request body or a price shown in the UI.
- Adjust expects major units (
149.99), while most payment providers report minor units (14999). Convert with the currency's exponent — not every currency has two decimals. - Send the ISO 4217 currency of the transaction. Adjust converts to the reporting currency with its own daily rates; converting in the backend first makes revenue irreconcilable with the payment source.
- Adjust's minimum accepted revenue is
0.001. Zero-value events (free trials, 100% vouchers) are sent without the revenue parameters. created_at_unixis the capture time reported by the provider — not the time the worker sends the request.
// shared/money.ts — integer arithmetic only, no floating point
const EXPONENT: Record<string, number> = {
JPY: 0, KRW: 0,
KWD: 3, BHD: 3, OMR: 3, JOD: 3, TND: 3, LYD: 3, IQD: 3,
}; // ISO 4217; default 2. Check your provider's rules for exceptions.
export function toMajorUnits(minor: number | bigint, currency: string): string {
const exp = EXPONENT[currency.toUpperCase()] ?? 2;
const v = BigInt(minor);
if (v < 0n) throw new Error('Adjust does not accept negative revenue');
const s = v.toString().padStart(exp + 1, '0');
return exp === 0 ? s : `${s.slice(0, -exp)}.${s.slice(-exp)}`;
}
// toMajorUnits(14999, 'SAR') → "149.99" toMajorUnits(12500, 'KWD') → "12.500"
Refunds and chargebacks
Adjust does not accept negative revenue, so a refund cannot cancel a purchase inside Adjust. Send it as a separate event without the revenue parameters and carry the refunded amount in callback parameters. Net revenue is then calculated in BI from raw data or callbacks.
Subscription renewals
Renewals happen on the store's side while the app is usually closed. The backend receives them as App Store Server Notifications or Google Play Real-time Developer Notifications, verifies them, and records an S2S event for the device that made the original purchase.
12Request Parameters
Parameter names are case-sensitive. The table lists what this integration sends; Adjust's S2S reference has the complete list.
| Parameter | Status | Format | Source in the backend |
|---|---|---|---|
s2s | Required | 1 | Constant |
app_token | Required | App token | Configuration, by platform |
event_token | Required | Event token | Event catalog, by platform |
adid | Always send | 32-character hex | Device context |
idfa / gps_adid | When available | Raw value from the SDK | Device context |
idfv | Backup (iOS) | Raw value from the SDK | Device context |
created_at_unix | Always send | Unix seconds | Outbox occurred_at |
environment | Always send | sandbox | production | Configuration — defaults to production if missing |
revenue | Revenue events | Major units, minimum 0.001 | Provider confirmation (§11) |
currency | With revenue | ISO 4217 | Provider confirmation |
callback_params | Optional | Flat JSON, string values | Visible in raw data exports and callbacks |
partner_params | Optional | Flat JSON, string values | Forwarded to linked media partners |
ip_address | Recommended | IPv4 only | The user's request — omit for webhook-originated events |
Device IP address
ip_address must be the user's device address, captured from the app's own request (checkout, device-context call). For events triggered by a webhook there is no device request — omit the parameter rather than sending the server's or the provider's IP.
// shared/client-ip.ts
import { isIPv4 } from 'node:net';
import type { Request } from 'express';
/** Requires app.set('trust proxy', …) to match the load balancer setup. */
export function clientIpv4(req: Request): string | undefined {
const ip = (req.ip ?? '').replace(/^::ffff:/, ''); // IPv4-mapped IPv6
return isIPv4(ip) ? ip : undefined; // Adjust accepts IPv4 only
}
Example request
POST /event HTTP/1.1
Host: s2s.adjust.com
Authorization: Bearer <S2S_TOKEN>
Content-Type: application/x-www-form-urlencoded
s2s=1&app_token=<APP_TOKEN>&event_token=<EVENT_TOKEN>&adid=<ADID>
&created_at_unix=1763550000&environment=sandbox&revenue=149.99¤cy=SAR
&callback_params=%7B%22order_id%22%3A%22ord_123%22%7D
Line breaks in the body are for readability only — the real body is one line.
13Responses & Error Handling
A 200 response means Adjust accepted the event. Every other response returns an error code and a message that names the cause. The worker maps each one to an action.
| HTTP | Adjust message | Meaning | Worker action |
|---|---|---|---|
| 200 | OK | Event accepted | sent |
| 400 | Ignoring event, earlier unique event tracked | Unique event already recorded for this device | dropped — expected |
| 400 | Bad event state | Event timestamp conflicts with the device's history, e.g. earlier than its install | dropped — investigate if frequent |
| 400 | Invalid app token / event token / callback parameters / revenue | Configuration or payload bug | failed + alert |
| 401 | Failed to authorize request | S2S token not authorised for this request, e.g. missing the Events scope | failed + alert |
| 403 | App is inactive / Tracking disabled / Event token blocklisted | Account-side block | failed + alert |
| 404 | Device not found | Adjust does not know the adid in this environment yet | retry a few times, then failed |
| 404 | App token not found | Wrong app token | failed + alert |
| 413 | Request size too large | Request above 1 MB — too many custom parameters | failed + alert |
| 451 | Device is opted out | The user exercised a privacy right (e.g. forget-me) | dropped — never retry |
| 5xx | Internal error | Temporary problem on Adjust's side | retry with backoff |
| — | Network error / timeout | No response received | retry with backoff (§8) |
// adjust/adjust-s2s.client.ts (continued)
export function classifyS2sResponse(status: number, body: string): S2sResult {
if (status === 200) return { kind: 'ok' };
const msg = body.toLowerCase();
if (status >= 500 || status === 429) return { kind: 'retry', status, body };
if (status === 404 && msg.includes('device not found')) return { kind: 'retry', status, body };
if (status === 451) return { kind: 'drop', status, body, reason: 'device_opted_out' };
if (status === 400 && msg.includes('earlier unique event')) {
return { kind: 'drop', status, body, reason: 'unique_already_tracked' };
}
if (status === 400 && msg.includes('bad event state')) {
return { kind: 'drop', status, body, reason: 'bad_event_state' };
}
// Tokens, account state or payload: a human has to fix it, retrying will not help.
return { kind: 'alert', status, body };
}
14S2S Security & Secrets
Without S2S authentication, anyone who knows an app token and an event token can inject events — including revenue — into the account. The S2S token closes that gap, but only once enforcement is switched on.
Store the token as a secret
Keep it in the secrets manager and inject it as ADJUST_S2S_TOKEN. It never goes into the mobile app, a frontend bundle, a repository or a log line. Use a token scoped to Events only.
Verify before enforcing
Run in production with the token for a period while authentication is still off, and confirm that every request carries the Authorization header — including those from scripts, back-office tools and any other service that calls the S2S endpoint.
Enable S2S authentication
In Protection → S2S Security, switch on Enable S2S authentication. From that moment Adjust rejects requests without a valid token. Adjust recommends having the setup validated by the Adjust account team or support before this step.
Rotate without downtime
Create a new token, deploy it, confirm traffic on it, then deactivate the old one. Keep at least one active token: if all tokens are deactivated, Adjust switches authentication off automatically.
Keep secrets and identifiers out of logs
// shared/redact.ts — use in loggers, HTTP interceptors and error reporters
export const redactAdid = (adid?: string | null) => (adid ? `${adid.slice(0, 6)}…` : adid);
// Never log the request headers of AdjustS2sClient. If an HTTP logging
// interceptor is global, exclude the Authorization header explicitly.
15Consent, Privacy & Residency
Backend events follow the same consent rules as SDK events. The backend usually does not see the consent prompt, so the app has to pass the decision along.
Consent
- Where measurement requires consent (for example under GDPR, KVKK or PDPL, as defined by the project's legal team), the app reports device context only after consent, and includes the consent state in the call.
- The tracker skips users whose current consent does not allow measurement: no outbox row, or a row with status
droppedfor auditability. - When a user is forgotten through the SDK, Adjust answers backend events for that device with
451. The worker drops them; the backend should also delete the device context. - Never put e-mail addresses, phone numbers, names or national IDs into
callback_paramsorpartner_params. Partner parameters leave Adjust and go to ad networks.
Data residency
If data residency is active for the app, every sender must use the regional host. Check the app's Protection tab in the dashboard first: if residency is not active, keep the default host.
| Region | S2S base URL |
|---|---|
| Default (no residency) | https://s2s.adjust.com |
| EU | https://s2s.eu.adjust.com |
| USA | https://s2s.us.adjust.com |
| Türkiye | https://s2s.tr.adjust.com |
| KSA | https://s2s.ksa.adjust.com |
ADJUST_S2S_BASE_URL therefore loses events without an obvious error — confirm the host before the first production send.
16Callbacks & Data Exports
This guide covers data going into Adjust. Data coming out of Adjust is configured separately — and it is the most common source of confusion in S2S projects.
| Direction | Mechanism | Covered by |
|---|---|---|
| App → Adjust | Adjust SDK: installs, sessions, SDK events | Platform guide |
| Backend → Adjust | S2S Events API | This guide |
| Adjust → your systems | Server callbacks (real time) and raw data exports (cloud storage) | Dashboard configuration |
- Callbacks and exports include S2S events exactly like SDK events, with their attribution. They are the place to see
callback_params— those values do not appear in dashboard reports. - They are not retrospective. Enable them before launch if BI or CDP work is planned.
- If callbacks are sent to this NestJS service: the endpoint must be publicly reachable, answer
200quickly and be idempotent, because failed deliveries are retried. Protect it with a long random secret in the callback URL.
17Testing & QA
Test in three layers: one manual request to prove the credentials, unit tests for the request format, and end-to-end tests on staging with real test devices in sandbox.
Smoke test with a test device
Take the adid of a registered test device from the Testing Console and send one sandbox event. A 200 response and the event in the Testing Console prove that tokens, host and device are correct.
curl -sS -X POST "https://s2s.adjust.com/event" \
-H "Authorization: Bearer $ADJUST_S2S_TOKEN" \
--data-urlencode "s2s=1" \
--data-urlencode "app_token=$APP_TOKEN" \
--data-urlencode "event_token=$EVENT_TOKEN" \
--data-urlencode "adid=$TEST_DEVICE_ADID" \
--data-urlencode "created_at_unix=$(date +%s)" \
--data-urlencode "environment=sandbox" \
--data-urlencode "revenue=1.00" \
--data-urlencode "currency=SAR" \
--data-urlencode 'callback_params={"order_id":"qa-0001"}'
Unit tests
// adjust/adjust-s2s.client.spec.ts — Vitest (Jest needs Node.js 24.9+ for ESM-only NestJS 12)
import { describe, expect, it, vi } from 'vitest';
import { AdjustS2sClient, classifyS2sResponse } from './adjust-s2s.client.js';
import type { AdjustConfig } from './adjust.config.js';
describe('AdjustS2sClient', () => {
const cfg = { environment: 'sandbox', baseUrl: 'https://s2s.adjust.com',
s2sToken: 't0k3n', timeoutMs: 10000 } as AdjustConfig;
it('sends a form-encoded revenue event with the Bearer token', async () => {
const fetchMock = vi.spyOn(globalThis, 'fetch')
.mockResolvedValue(new Response('{"status":"OK"}', { status: 200 }));
const result = await new AdjustS2sClient(cfg).sendEvent({
appToken: 'app', eventToken: 'evt', adid: 'a'.repeat(32),
createdAtUnix: 1763550000,
revenue: { amount: '12.500', currency: 'KWD' },
callbackParams: { order_id: 'ord_1' },
});
const [url, init] = fetchMock.mock.calls[0];
const body = new URLSearchParams(String(init!.body));
expect(result).toEqual({ kind: 'ok' });
expect(url).toBe('https://s2s.adjust.com/event');
expect((init!.headers as Record<string, string>).Authorization).toBe('Bearer t0k3n');
expect(body.get('environment')).toBe('sandbox');
expect(body.get('revenue')).toBe('12.500');
expect(JSON.parse(body.get('callback_params')!)).toEqual({ order_id: 'ord_1' });
});
it.each([
[451, 'Device is opted out', 'drop'],
[400, 'Ignoring event, earlier unique event tracked', 'drop'],
[400, 'Invalid event token', 'alert'],
[404, 'Device not found', 'retry'],
[500, 'Internal error', 'retry'],
])('classifies %i "%s" as %s', (status, message, kind) => {
expect(classifyS2sResponse(status, JSON.stringify({ error: message })).kind).toBe(kind);
});
});
End-to-end on staging (sandbox)
Run the real flows on a test device against staging: install, purchase, refund, renewal. Follow each through the outbox row, the worker log and the Testing Console. In dashboard reports, enable the sandbox filter — sandbox data is hidden otherwise.
QA matrix
| Scenario | Expected result |
|---|---|
| Provider sends the same webhook twice | One outbox row, one event in Adjust |
| Adjust unreachable (egress blocked on staging) | Checkout succeeds; rows stay pending and are delivered after the block is lifted |
| Wrong event token in the catalog | Row failed, alert raised, nothing retried in a loop |
| User without device context | Row no_device, counted in monitoring, not sent |
| Sandbox adid sent to production | 404 Device not found, limited retries, then failed |
| Purchase in a three-decimal currency (KWD / BHD / OMR) | Revenue in Adjust matches the provider amount exactly |
| Refund | Separate refund event, no revenue added to totals |
| Two events for one device created out of order | Worker sends them in occurred_at order; both accepted |
| Repeat of a unique event | 400 "earlier unique event tracked", row dropped, no alert |
| Staging configuration | Every request has environment=sandbox; nothing appears in production reports |
18Release Plan
| Phase | Environment | Goal | Exit criteria |
|---|---|---|---|
| 1. Shadow mode | Staging → production | Outbox rows are written with ADJUST_S2S_ENABLED=false; nothing is sent. | Rows are complete and correct for every event type; no_device rate known. |
| 2. Sandbox delivery | Staging | Worker sends to Adjust with environment=sandbox. | QA matrix in §17 passes. |
| 3. Production delivery | Production | Enable sending with the S2S token; authentication not yet enforced. | [7] days with no unexplained failed rows; reconciliation within tolerance. |
| 4. Enforce S2S authentication | Production | Switch on Enable S2S authentication. | No authorisation errors after the switch. |
| 5. SDK event removal (transitions only) | App release | Remove SDK events now owned by the backend. | Event counts in BI stable across the switch. |
| 6. Post-launch validation | Production | Confirm data quality before relying on S2S revenue for optimisation. | See §19. |
pending when sending is enabled. Decide before the switch whether to send them (they must be younger than the age limit) or mark them dropped — especially if the SDK was still sending the same events during that period.
19Post-Launch Monitoring
The outbox table is the monitoring source. Every event the backend decided to send is a row with a final status, so gaps can be explained row by row.
| Metric | What it reveals | Alert when |
|---|---|---|
Age of the oldest pending row | Worker stopped or Adjust unreachable | > [30] minutes |
failed rows | Token, account or payload problem | Any new row |
no_device share of events | App not reporting device context | > [2]% |
dropped rows by reason | Opt-outs, unique repeats, timestamp conflicts | Sudden change against baseline |
| Backend revenue vs Adjust revenue (per event, per currency) | End-to-end completeness | Unexplained gap > [x]% |
-- Daily delivery summary per event
SELECT event_key, status, count(*) AS events,
sum(revenue_amount::numeric) AS revenue, revenue_currency
FROM adjust_outbox
WHERE occurred_at >= current_date - 1 AND occurred_at < current_date
GROUP BY event_key, status, revenue_currency
ORDER BY event_key, status;
sent rows against raw data or callbacks in the transaction currency, and explain the remaining difference with the outbox statuses (no_device, dropped, failed) before treating it as data loss.
20Implementation Readiness
Assign an owner and resolve each decision before its dependent implementation or release step. Use this table as the project readiness register.
| # | Decision | Owner | Blocking? |
|---|---|---|---|
| 1 | Final event taxonomy and owner (SDK or S2S) per event | Product / Measurement Partner | Blocks event catalog |
| 2 | Delivery mechanism: database outbox or BullMQ | Backend | Blocks worker implementation |
| 3 | Device selection rule for server-originated events | Backend / Measurement Partner | Blocks refunds and renewals |
| 4 | Refund representation and net-revenue calculation in BI | Finance / BI | Blocks refund event |
| 5 | Renewal route: custom S2S event or Adjust Subscriptions | Product / Measurement Partner | Blocks renewal event |
| 6 | Which events are unique | Measurement Partner | Blocks dashboard setup |
| 7 | Consent source and rules per market | Legal / Product | Blocks production sending |
| 8 | Data residency status and S2S host | Legal | Blocks production sending |
| 9 | S2S token ownership, storage and rotation | Security / DevOps | Blocks enforcement |
| 10 | Callback / raw export destination | BI | Time-critical — not retrospective |
| 11 | Retention period for device identifiers | Legal / Security | Blocks device-context table |
21Go-Live Checklist
- Final taxonomy signed off; every event has exactly one owner.
- No business action is sent by both the SDK and the backend.
- All production event tokens in the event catalog only.
- App tokens selected by device platform.
- Production sends
environment=production; staging sendssandbox. - S2S host matches the data residency status.
- S2S token in the secrets manager, scoped to Events.
- Authorization header absent from all logs.
- App reports adid and available advertising IDs after login and on app start.
- Outbox row written in the same transaction as the business change.
- Dedupe keys come from provider or order IDs.
- Duplicate webhook validated: one event in Adjust.
- Revenue from verified provider data, in major units.
- Three-decimal currencies validated.
- Refund event carries no revenue parameters.
- Events sent in chronological order per device.
- Retry, drop and alert paths validated.
- Consent respected; no personal data in custom parameters.
- Callbacks / raw export decided before launch.
- Monitoring and alerts live.
- S2S authentication enforcement scheduled after verification.
22Technical References
Adjust updates its APIs and dashboard regularly. Re-check parameter names and response messages against the current documentation before writing production code.
Adjust — S2S API
- S2S API overview — endpoints, device identifiers, error codes
- S2S events — parameters, ordering rule, 58-day limit
- S2S security — tokens, scopes and enforcement
- Transition SDK to S2S events — moving an existing SDK event to the backend
- S2S developer guide — identifiers and recommended parameters
Adjust — SDK device identifiers
- Android — device information —
getAdid,getGoogleAdId - iOS — device information —
adid,idfa,idfv - Adjust Help Center — events, Testing Console, data residency, callbacks
NestJS
- Migration guide — NestJS 11 → 12: Node.js, ESM, config validation
- Configuration —
ConfigModule,registerAs, validation - Task scheduling —
@Cron - Queues — BullMQ integration
- Validation —
class-validatorDTOs