Skip to content

Common patterns

This tutorial covers patterns you’ll hit once you’re past the “first call” stage. Each section is independently useful — skip to what you need.

Pagination across multiple pages

The standard list response shape:

{
"data": [ /* array of resources */ ],
"total": 248,
"page": 1,
"limit": 25,
"total_pages": 10
}

Default limit is 25, max is 100. To traverse all pages:

With the SDK (preferred):

async function* allUsers() {
let page = 1;
while (true) {
const result = await client.users.list({ page, limit: 100 });
yield* result.data;
if (page >= result.total_pages) return;
page++;
}
}
for await (const user of allUsers()) {
console.log(user.email);
}

The async generator pattern lets you process users as they arrive without loading all 10K into memory.

With raw fetch:

const allUsers: User[] = [];
let page = 1;
while (true) {
const r = await fetch(
`${process.env.ATMANID_BASE_URL}/api/v1/users?page=${page}&limit=100`,
{ headers: { Authorization: `Bearer ${process.env.ATMANID_API_KEY}` } }
);
const result = await r.json();
allUsers.push(...result.data);
if (page >= result.total_pages) break;
page++;
}

Anti-pattern to avoid: don’t request limit > 100 — the API silently caps it at 100, so a loop that assumes it got more rows per page will miscount. Always check total_pages on the FIRST response and stop pagination at the boundary; don’t loop forever waiting for an empty data array.

Error handling

Every API error has the same body — { "error": { "code", "message", "request_id", "details"? } } — and you branch on error.code, never on the message. The SDK turns that into three error classes, all extending AtmanIDError:

  • AtmanIDClientError — any 4xx. Carries status, code (e.g. UNAUTHENTICATED, RBAC_DENIED, NOT_FOUND, VALIDATION_ERROR, RATE_LIMITED) and details
  • AtmanIDServerError — any 5xx, after the SDK’s one automatic retry
  • AtmanIDNetworkError — timeout, DNS failure, connection reset, after the one automatic retry

The pattern:

import {
AtmanIDClientError,
AtmanIDServerError,
AtmanIDNetworkError,
} from './vendor/atmanid-client';
try {
return await client.users.get(userId);
} catch (err) {
if (err instanceof AtmanIDClientError) {
switch (err.code) {
case 'UNAUTHENTICATED': // 401 — key invalid, expired, or revoked
console.error('[atmanid] auth failed:', err.message);
break;
case 'RBAC_DENIED': // 403 — key lacks the scope (details.missing lists it)
console.error('[atmanid] forbidden:', err.details);
break;
case 'VALIDATION_ERROR': // 400 — body failed validation; details.fieldErrors per field
console.error('[atmanid] validation failed:', err.details);
break;
case 'RATE_LIMITED': // 429 — back off, see Rate limit handling below
break;
default:
if (err.status === 404) console.error('[atmanid] not found'); // or you can't see it
}
throw err;
} else if (err instanceof AtmanIDServerError || err instanceof AtmanIDNetworkError) {
// 5xx / transport — the SDK already retried once
console.error('[atmanid] request failed:', err.message, err.requestId);
throw err;
} else {
throw err; // re-throw unknown
}
}

Every error class carries err.requestId (the AtmanID-side correlation ID). Always log the requestId when surfacing errors — it lets the AtmanID team trace back to the exact server-side log entry if you need support.

Retries

The SDK retries once, after a short jittered pause, on 5xx and network errors. It never retries a 4xx — including 429 — because those need a decision from you.

For more persistent retries (a batch job that should ride out a longer blip, or back off on 429), wrap calls in a structured retry pattern:

async function withRetry<T>(
fn: () => Promise<T>,
options: { maxAttempts?: number; baseDelayMs?: number } = {}
): Promise<T> {
const maxAttempts = options.maxAttempts ?? 3;
const baseDelayMs = options.baseDelayMs ?? 1000;
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
return await fn();
} catch (err) {
if (attempt === maxAttempts) throw err;
// Don't retry permanent failures: any 4xx except rate limiting
if (err instanceof AtmanIDClientError && err.code !== 'RATE_LIMITED') throw err;
const delay = baseDelayMs * Math.pow(2, attempt - 1); // exponential
await sleep(delay);
}
}
throw new Error('unreachable');
}
const sleep = (ms: number) => new Promise(r => setTimeout(r, ms));
const result = await withRetry(() => client.users.list({ page: 1, limit: 100 }));

Critical: not every mutation is idempotent by default. Identity-creating endpoints (/api/v1/agents, /api/v1/jml/joiner) take a required idempotency_key body field — the same key within 24h returns the cached response instead of creating a duplicate:

// idempotency_key is a BODY field (not a header) — use a key stable
// across retries of the same logical operation:
await client.agents.register({
idempotency_key: `retry-demo-${workflowRunId}`,
name: 'ci-deploy-bot',
type: 'ci-automation',
owner_team: 'platform-eng',
owner_email: 'dev.torres@example.com',
});
// Repeat with the same idempotency_key → same response, no duplicate creation

Rate limit handling

A standard-tier API key is limited to 60 requests per minute (partner-tier keys get 600). Hitting the limit returns 429 with error.code RATE_LIMITED and a Retry-After header in seconds.

Reactive handling (catch the 429, back off):

async function callWithRateLimit<T>(fn: () => Promise<T>): Promise<T> {
try {
return await fn();
} catch (err) {
if (err instanceof AtmanIDClientError && err.code === 'RATE_LIMITED') {
// The SDK error doesn't expose response headers; the per-key
// limit's Retry-After is 60 s, so wait a full window.
console.warn('Rate limited; sleeping 60s');
await sleep(60_000);
return fn(); // single retry — escalate if it 429s again
}
throw err;
}
}

Proactive handling (token bucket, prevent 429s):

For high-volume integrations, implement a client-side token bucket sized below your limit. The SDK doesn’t ship one; libraries like bottleneck work:

import Bottleneck from 'bottleneck';
const limiter = new Bottleneck({
reservoir: 50, // start with 50 tokens (10 below the 60/min limit)
reservoirRefreshAmount: 50,
reservoirRefreshInterval: 60_000,
maxConcurrent: 10,
minTime: 100,
});
const result = await limiter.schedule(() => client.users.list({ page: 1 }));

Anti-pattern: never retry 429 responses with no delay or fixed-interval backoff — you’ll cause cascading failures and may get flagged for abuse. Always honor Retry-After.

Webhook signature verification

Every AtmanID webhook delivery is signed. Your endpoint must verify the signature before trusting the payload — otherwise anyone who learns your URL can forge events.

Header Purpose
X-Webhook-Signature: sha256=<hex> HMAC SHA-256 of the raw request body, keyed with your subscription’s signing secret
X-AtmanID-Signature: t=<unix>,v1=<hex> HMAC SHA-256 of <t>.<raw body>, signed at each attempt so you can refuse a replay; after a rotation, a second v1 signed with the old secret for the overlap window. See the webhook events reference.
X-Delivery-ID: <uuid> Identifies this delivery; the same value is sent on every retry of it
X-Attempt-Number: <n> 1 for the first attempt, then 2, 3… on retries
X-Event-Type: <type> The event type, also present in the body
X-Webhook-ID: <uuid> The subscription the delivery belongs to

The body is JSON with a stable id for the event, the event_type, the timestamp when the event occurred, your tenant_id, api_version and data. Because the signature covers the whole body, those fields are protected too.

The signing secret is returned once, when you create the subscription or rotate its secret — capture it then; it cannot be retrieved later. AtmanID stores it encrypted.

import { createHmac, timingSafeEqual } from 'crypto';
function verifyWebhook(rawBody: string, sigHeader: string | null, secret: string): boolean {
if (!sigHeader?.startsWith('sha256=')) return false;
const provided = Buffer.from(sigHeader.slice(7), 'hex');
const expected = createHmac('sha256', secret).update(rawBody).digest();
// Constant-time comparison; lengths must match first.
return provided.length === expected.length && timingSafeEqual(provided, expected);
}
const processedEvents = new Set<string>(); // production: a store with a TTL of a day or more
export async function POST(req: Request) {
const rawBody = await req.text(); // raw bytes — verify BEFORE parsing
if (!verifyWebhook(rawBody, req.headers.get('X-Webhook-Signature'), process.env.ATMANID_WEBHOOK_SECRET!)) {
return new Response('Invalid signature', { status: 401 });
}
const event = JSON.parse(rawBody);
if (processedEvents.has(event.id)) {
return new Response('Already processed', { status: 200 }); // a retry or a replay
}
processedEvents.add(event.id);
// ... process event ...
return new Response('OK', { status: 200 });
}

The four things that matter:

  1. Raw body bytes — verify against the bytes the request arrived with, not a re-serialised JSON object. Serialisation changes whitespace and key order, which breaks the HMAC. Read the body as text, verify, then parse.
  2. Constant-time comparison — use timingSafeEqual, never ===.
  3. Deduplicate on the event id. AtmanID retries any delivery that fails (a network error or a non-2xx response) up to six attempts in total, spread over roughly ten hours. Every attempt carries the same body, so the same id. Keying on id makes retries safe and also stops a captured delivery from being replayed into your system. Keep processed IDs for at least a day.
  4. Don’t reject on a short time window. The body’s timestamp is when the event happened, and a retry can legitimately arrive hours later. If you want a freshness check, allow at least twelve hours — deduplication on id is the real replay defence.

Test from the dashboard: in Platform Config → Integrations & API → Webhooks, every active subscription has a Send test event button that dispatches a synthetic WEBHOOK_TEST event signed with your real secret. Use this to verify your handler before relying on real events firing.

Idempotency for mutations

For any identity-creating mutation that should be safely retryable (e.g., a long-running workflow that might crash mid-execution), use the idempotency_key body field — it’s required on /api/v1/jml/joiner and /api/v1/agents:

// Generate a stable key for the logical operation
// (e.g., based on a workflow run ID — NOT Date.now(), which changes per attempt)
const idempotencyKey = `provision-${hrisEventId}`;
await client.jml.joiner({
idempotency_key: idempotencyKey,
email, first_name, last_name,
});
// Worker crashes mid-execution. On restart, retry with the SAME key:
await client.jml.joiner({
idempotency_key: idempotencyKey,
email, first_name, last_name,
});
// → Returns the cached response from the first call. No duplicate identity created.

Idempotency keys are scoped per-tenant + per-endpoint and stored for 24 hours.

Connection pooling + keep-alive

For high-volume integrations, reuse connections to avoid a TLS handshake per request. The SDK uses the runtime’s native fetch (undici on Node 18+), which keeps connections alive by default — so the main rule is to create one client and reuse it, rather than constructing a new AtmanIDClient per call:

// client.ts — one shared instance for the whole process
export const client = new AtmanIDClient({
apiKey: process.env.ATMANID_API_KEY!,
baseUrl: process.env.ATMANID_BASE_URL,
});

The SDK has no httpAgent option. If you need to tune the pool (e.g. maximum sockets per origin), configure undici’s global dispatcher in your process. On Vercel/Cloudflare Workers, the runtime manages connection pooling for you.

Where to go next

© AtmanID · Privacy