---
title: "Developer Quickstart: Building a Multi-ATS Link UI for Greenhouse, Lever & More"
slug: developer-quickstart-building-a-multi-ats-link-ui-for-b2b-saas
date: 2026-05-18
author: Roopendra Talekar
categories: [Guides, By Example]
excerpt: "A developer quickstart for integrating Greenhouse, Lever, and Workable simultaneously - with auth patterns, pagination translation, webhook verification, reconciliation jobs, and debugging tips."
tldr: "Stop building separate OAuth flows, pagination parsers, and webhook handlers for each ATS. Use an embeddable Link UI and unified API to connect Greenhouse, Lever, and Workable with one codebase - includes runnable examples for auth, sync, and monitoring."
canonical: https://truto.one/blog/developer-quickstart-building-a-multi-ats-link-ui-for-b2b-saas/
---

# Developer Quickstart: Building a Multi-ATS Link UI for Greenhouse, Lever & More


Your sales team just closed a verbal commit with a Series C HR tech buyer. The catch: they use Lever, the next prospect in your pipeline uses Greenhouse, and the enterprise lead from last month uses Workable. Your engineering lead estimates four to six weeks per applicant tracking system (ATS) for the bespoke OAuth flows, custom field mappings, settings UIs, and webhook plumbing. That is twelve to eighteen weeks of senior engineering work before a single candidate record syncs. The deal is effectively stalled before the ink is dry.

The ATS market is structurally highly fragmented, making point-to-point integrations unscalable. <cite index="6-2">The global applicant tracking system market is anticipated to rise from about USD 3.28 billion in 2025 to USD 4.88 billion by 2030, growing at a CAGR of 8.2% during the forecast period.</cite> That growth is spread across hundreds of niche and enterprise vendors. Your enterprise prospects use Greenhouse and Workday Recruiting. Your scale-up prospects use Lever and Ashby. Your SMB customers use Workable, Recruitee, JazzHR, and Teamtailor. There is no single ATS to integrate with—there is a long tail you have to support to win deals.

Building SaaS integrations in-house is a massive capital expense. Developing a mid-scale SaaS product with third-party integrations typically costs between $60,000 and $150,000 to build, with ongoing maintenance adding 15-20% annually. That number balloons fast once you account for token-refresh fires, schema drift, and the inevitable undocumented API quirks.

This quickstart is a technical blueprint for collapsing that months-long integration nightmare into a single afternoon. We will implement an embeddable Link UI that handles authentication, token lifecycles, and configuration across multiple ATS providers in a single flow. By the end of this guide, you will know exactly how to drop in a secure authentication UI and start reading and writing unified candidate data.

## Quickstart: Build a working multi-ATS sync in one afternoon

If you want to skip the theory and prototype a working Greenhouse + Lever + Workable sync today, this is the minimum viable approach: one Link UI to capture credentials, one webhook receiver, one paginated historical sync, and one reconciliation cron. The rest of this guide unpacks each step with production hardening. The strategy is the same across providers - the unified API absorbs the per-vendor differences so you write the loop once.

### Boilerplate: env vars, secrets, permissions

Set these environment variables before you start:

```bash
# Truto platform credentials
TRUTO_API_KEY=sk_live_...              # Server-side only, never expose to the browser
TRUTO_WEBHOOK_SECRET=whsec_...         # Used to verify X-Truto-Signature on inbound webhooks

# Your app
DATABASE_URL=postgres://...
WEBHOOK_PUBLIC_URL=https://api.yourapp.com/webhooks/truto
```

Provider-side permissions to line up when you register your partner app with each ATS:

- **Greenhouse Harvest:** the authorizing user must have Site Admin privileges for list endpoints. Non-admin users can complete OAuth but hit 403s on reads.
- **Lever:** your OAuth client needs partner-tier access. Sandbox and production use different auth servers, so keep credentials separated.
- **Workable:** your partner app receives a `client_id` and `client_secret` from Workable directly, and you need to capture the customer's subdomain during the connect flow to build the correct base URL.

A sample Postgres schema for the target table used throughout the snippets below:

```sql
CREATE TABLE candidates (
  external_id           TEXT NOT NULL,
  integrated_account_id TEXT NOT NULL,
  first_name            TEXT,
  last_name             TEXT,
  email                 TEXT,
  raw_payload           JSONB,
  updated_at            TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  PRIMARY KEY (external_id, integrated_account_id)
);

CREATE TABLE sync_state (
  integrated_account_id TEXT PRIMARY KEY,
  last_synced_at        TIMESTAMPTZ NOT NULL
);
```

### Step 1 - Connect with Link UI (sample OAuth flows)

Issue a short-lived Link Token from your backend, mount the Link component in your frontend, and hand off the OAuth dance to the platform. On success you get back an `integrated_account_id` - the only handle you need for every subsequent call. You never see the underlying Greenhouse, Lever, or Workable tokens.

```typescript
// Backend: issue a tenant-scoped link token
app.post('/api/link-token', async (req, res) => {
  const response = await fetch('https://api.truto.one/link-token', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${process.env.TRUTO_API_KEY}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      tenant_id: req.user.tenantId,
      integrations: ['greenhouse', 'lever', 'workable', 'ashby'],
      unified_model: 'ats'
    })
  });
  const { link_token } = await response.json();
  res.json({ link_token });
});
```

The frontend renders the Link component, and once the user completes OAuth for whichever ATS they picked, persist the returned `integrated_account_id` against your tenant record. The full React example is in the deep-dive below.

### Step 2 - Subscribe to unified webhooks (sample verification code)

Configure Truto's webhook destination to point at your public endpoint. Provider-native events (Greenhouse candidate created, Lever stage change, Workable application update) arrive as normalized `ats.*` events signed with `X-Truto-Signature`. You verify one signature scheme, not three.

**Node.js:**

```typescript
import crypto from 'crypto';
import express from 'express';

const app = express();

// Preserve the raw body for HMAC verification
app.use('/webhooks/truto', express.raw({ type: 'application/json' }));

app.post('/webhooks/truto', (req, res) => {
  const signature = req.header('x-truto-signature') || '';
  const expected = crypto
    .createHmac('sha256', process.env.TRUTO_WEBHOOK_SECRET!)
    .update(req.body)
    .digest('hex');

  const valid = signature.length === expected.length &&
    crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected));

  if (!valid) return res.status(401).end();

  const event = JSON.parse(req.body.toString());
  res.status(200).end();          // ack fast
  queue.enqueue(event);           // process async
});
```

**Python (Flask):**

```python
import hmac, hashlib, os
from flask import Flask, request, abort

app = Flask(__name__)
WEBHOOK_SECRET = os.environ["TRUTO_WEBHOOK_SECRET"].encode()

@app.post("/webhooks/truto")
def truto_webhook():
    signature = request.headers.get("x-truto-signature", "")
    expected = hmac.new(WEBHOOK_SECRET, request.data, hashlib.sha256).hexdigest()
    if not hmac.compare_digest(signature, expected):
        abort(401)

    event = request.get_json()
    # ack fast, enqueue for async processing
    queue.enqueue(event)
    return "", 200
```

### Step 3 - Historical sync / pagination loop (Node + Python examples)

After the connect completes, backfill everything the ATS already has. The unified pagination contract is identical across providers: pass `cursor`, read `next_cursor`, stop when it is null. On HTTP 429, back off using the standardized `ratelimit-reset` header and add jitter to avoid thundering-herd retries.

**Node.js:**

```typescript
import { Pool } from 'pg';
const pool = new Pool({ connectionString: process.env.DATABASE_URL });

async function backfillCandidates(
  integratedAccountId: string,
  filters: { updated_after?: string } = {}
): Promise<number> {
  let cursor: string | null = null;
  let synced = 0;

  do {
    const url = new URL('https://api.truto.one/unified/ats/candidate');
    url.searchParams.set('integrated_account_id', integratedAccountId);
    url.searchParams.set('limit', '100');
    if (cursor) url.searchParams.set('cursor', cursor);
    if (filters.updated_after) url.searchParams.set('updated_after', filters.updated_after);

    const res = await fetch(url, {
      headers: { 'Authorization': `Bearer ${process.env.TRUTO_API_KEY}` }
    });

    if (res.status === 429) {
      const reset = parseInt(res.headers.get('ratelimit-reset') || '5', 10);
      await new Promise(r => setTimeout(r, reset * 1000 + Math.random() * 1000));
      continue;
    }
    if (!res.ok) throw new Error(`Sync failed: ${res.status}`);

    const { result, next_cursor } = await res.json();

    for (const c of result) {
      await pool.query(
        `INSERT INTO candidates
           (external_id, integrated_account_id, first_name, last_name, email, raw_payload, updated_at)
         VALUES ($1, $2, $3, $4, $5, $6, NOW())
         ON CONFLICT (external_id, integrated_account_id)
         DO UPDATE SET first_name  = EXCLUDED.first_name,
                       last_name   = EXCLUDED.last_name,
                       email       = EXCLUDED.email,
                       raw_payload = EXCLUDED.raw_payload,
                       updated_at  = NOW()`,
        [c.id, integratedAccountId, c.first_name, c.last_name, c.primary_email, c]
      );
      synced++;
    }

    cursor = next_cursor;
  } while (cursor);

  return synced;
}
```

**Python:**

```python
import os, time, random, requests, psycopg
from psycopg.types.json import Json

API = "https://api.truto.one/unified/ats/candidate"
HEADERS = {"Authorization": f"Bearer {os.environ['TRUTO_API_KEY']}"}

def backfill_candidates(integrated_account_id: str, conn: psycopg.Connection,
                        updated_after: str | None = None) -> int:
    cursor, synced = None, 0
    while True:
        params = {"integrated_account_id": integrated_account_id, "limit": 100}
        if cursor:
            params["cursor"] = cursor
        if updated_after:
            params["updated_after"] = updated_after

        res = requests.get(API, headers=HEADERS, params=params, timeout=30)

        if res.status_code == 429:
            reset = int(res.headers.get("ratelimit-reset", "5"))
            time.sleep(reset + random.random())
            continue
        res.raise_for_status()
        payload = res.json()

        with conn.cursor() as cur:
            for c in payload["result"]:
                cur.execute(
                    """
                    INSERT INTO candidates
                        (external_id, integrated_account_id, first_name,
                         last_name, email, raw_payload, updated_at)
                    VALUES (%s, %s, %s, %s, %s, %s, NOW())
                    ON CONFLICT (external_id, integrated_account_id)
                    DO UPDATE SET first_name  = EXCLUDED.first_name,
                                  last_name   = EXCLUDED.last_name,
                                  email       = EXCLUDED.email,
                                  raw_payload = EXCLUDED.raw_payload,
                                  updated_at  = NOW()
                    """,
                    (c["id"], integrated_account_id,
                     c.get("first_name"), c.get("last_name"),
                     c.get("primary_email"), Json(c)),
                )
                synced += 1
        conn.commit()

        cursor = payload.get("next_cursor")
        if not cursor:
            return synced
```

### Step 4 - Reconciliation job (cron + sample upsert)

Webhooks drop under network partitions and provider outages. Run the same pagination loop on a 6-12 hour cadence with an `updated_after` filter to catch anything the webhook handler missed. The upsert is idempotent, so re-running is safe.

```
# /etc/cron.d/truto-reconcile
0 */6 * * * app cd /srv/app && node ./jobs/reconcile.js >> /var/log/reconcile.log 2>&1
```

The job itself is a thin wrapper around the Step 3 loop, scoped to records changed since the last watermark:

```typescript
async function reconcile(integratedAccountId: string) {
  const startedAt = new Date().toISOString();

  const { rows } = await pool.query(
    'SELECT last_synced_at FROM sync_state WHERE integrated_account_id = $1',
    [integratedAccountId]
  );
  const lastSyncedAt = rows[0]?.last_synced_at?.toISOString()
    ?? new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString();

  const count = await backfillCandidates(integratedAccountId, { updated_after: lastSyncedAt });

  await pool.query(
    `INSERT INTO sync_state (integrated_account_id, last_synced_at)
     VALUES ($1, $2)
     ON CONFLICT (integrated_account_id)
     DO UPDATE SET last_synced_at = EXCLUDED.last_synced_at`,
    [integratedAccountId, startedAt]
  );

  console.log(`Reconciled ${count} candidates for ${integratedAccountId}`);
}
```

That is the full loop end to end. Everything below expands each step with provider-specific gotchas, monitoring, and failure modes.

## The Multi-ATS Integration Bottleneck

Integration capabilities are a primary factor in software purchasing decisions. Effectively communicating software integration capabilities significantly expands buyer reach during the evaluation phase, according to Gartner's 2024 Global Software Buying Trends report. Yet, the broader integration data is brutal. <cite index="12-11,12-12">A MuleSoft survey of 1,050 enterprise IT leaders found that 95% of respondents struggle to integrate data across systems, and only 29% of applications are typically connected within organizations, on average.</cite> <cite index="17-17">Separate research indicates that 84% of all system integration projects fail or only partially succeed.</cite>

When a B2B SaaS company decides to build an ATS integration natively, they usually start with the market leader, like Greenhouse. The engineering team reads the documentation, sets up a developer account, and builds a bespoke OAuth 2.0 flow. They create database tables to store access tokens, refresh tokens, and expiration timestamps. They write a CRON job to refresh those tokens. They map the Greenhouse `Candidate` object to their internal schema.

Then the product manager asks for Lever.

As detailed in our [engineering guide to the Lever API](https://truto.one/blog/how-to-integrate-with-the-lever-api-2026-engineering-guide/), Lever's API uses different pagination strategies. Their OAuth implementation has slightly different token expiration logic. Their candidate schema nests custom fields entirely differently than Greenhouse. The engineering team has to abstract their original Greenhouse code, build a generic interface, and write a new Lever adapter. 

Then the product manager asks for Workable.

This cycle continues until a quarter of your engineering team is doing nothing but maintaining API adapters and debugging token refresh failures. Embedded iPaaS solutions attempt to solve this via visual workflow builders, but these are often overly complex and expensive for teams just needing a clean, embeddable connection UI and CRUD access. Other unified API providers force developers into rigid, standardized data models that frequently break on custom ATS fields.

We need a code-first, declarative approach that provides a unified schema without sacrificing access to custom fields. For a deeper teardown of why this is structurally hard, see our [guide on integrating Greenhouse, Lever, and Workable](https://truto.one/blog/how-to-integrate-multiple-ats-platforms-greenhouse-lever-workable/).

## What is an Embeddable Link UI?

A **Link SDK** is an embeddable JavaScript component that renders the authentication UI for third-party integrations directly inside your product. Instead of building a bespoke settings page for every ATS provider, you call one function—like `link.open('greenhouse')` or `link.open('lever')`—and embed a single component that handles the entire connection lifecycle.

**Core responsibilities of an embeddable Link UI:**
*   **Provider Selection:** Displays a searchable directory of supported integrations.
*   **Credential Capture:** Renders dynamic forms for API keys, subdomains, or custom headers based on the provider's auth requirements (e.g., Ashby uses admin-generated API keys, while Greenhouse uses OAuth).
*   **OAuth Lifecycle:** Manages the OAuth 2.0 authorization code flow, PKCE validation, and secure token storage.
*   **Post-Connection Configuration:** Handles provider-specific setup steps, like selecting default departments or mapping custom fields.
*   **Error Recovery:** Guides users through re-authentication if a token is permanently revoked or expired.

Here is how the architecture flows when a user connects their ATS via a Link UI:

```mermaid
sequenceDiagram
    participant User
    participant YourApp as Your App
    participant LinkUI as Link UI
    participant Truto
    participant ATS as ATS Provider

    User->>YourApp: Clicks "Connect ATS"
    YourApp->>Truto: Request Link Token (Tenant ID)
    Truto-->>YourApp: Returns link_token
    YourApp->>LinkUI: Initialize with Token and link.open()
    LinkUI->>User: Display Provider List (Greenhouse, Lever, etc.)
    User->>LinkUI: Selects Greenhouse
    LinkUI->>Truto: Initiate OAuth Flow
    Truto->>ATS: Redirect to Authorization URL
    ATS-->>User: Prompt for Consent
    User->>ATS: Approves Access
    ATS-->>Truto: Return Authorization Code + State
    Truto->>ATS: Exchange Code for Tokens
    ATS-->>Truto: Access + Refresh Tokens
    Truto-->>LinkUI: Connection Successful (integrated_account_id)
    LinkUI-->>YourApp: onSuccess Callback
    Note over Truto: Pre-schedules token refresh<br>before expiry via background task
```

The trade-off worth being honest about: an embeddable component gives up some pixel-perfect control over the connection screen. If your design system demands that every modal match your exact tokens and motion specs, you will burn time customizing themes. Most teams find that the time saved on OAuth boilerplate is well worth giving up some UI control. For deeper UX patterns on this, our [Link SDK design guide](https://truto.one/blog/how-to-build-and-document-a-high-converting-link-sdk-for-saas-integrations/) covers conversion principles in detail.

## Step 1: Configuring the Unified ATS API

Before we embed the Link UI, we need to understand how data is normalized across these disparate systems. Truto's [Unified ATS API](https://truto.one/blog/what-are-ats-integrations-2026-architecture-strategy-guide/) provides a standardized data model to interact with various recruiting platforms. It abstracts away provider-specific nuances, allowing developers to programmatically manage job postings, candidate pipelines, and interview scheduling through a single schema.

In Truto, an integration represents a third-party service. The architecture relies on three layers:

1.  **Integration Definition:** A JSON configuration describing how to talk to a third-party API (base URL, auth scheme, pagination).
2.  **Unified Model Mappings:** A mapping layer that translates between standardized schemas and each integration's native format.
3.  **Connected Accounts:** When a customer connects their account, Truto creates an integrated account storing credentials and context data.

Every request includes an `integrated_account_id` query parameter that routes the call to the right provider. Your code does not branch on Greenhouse vs. Lever. Rather than writing integration-specific code, Truto normalizes data using declarative JSONata mapping expressions. A unified `Candidate` object will always look like this, regardless of whether the data originated from Ashby, Greenhouse, or Workable:

```json
{
  "id": "12345",
  "first_name": "Jane",
  "last_name": "Doe",
  "primary_email": "jane.doe@example.com",
  "phone": "+1-555-0123",
  "applications": [
    {
      "id": "app_987",
      "job_id": "job_456",
      "status": "active",
      "stage": "interview"
    }
  ]
}
```

The entity model covers what you actually need for hiring workflows: `Jobs`, `Candidates`, `Applications`, `JobInterviewStages`, `Scorecards`, `Offers`, `Departments`, `Offices`, and `Attachments`. Here is a minimal sync that pulls all candidates across any ATS:

```typescript
const response = await fetch(
  `https://api.truto.one/unified/ats/candidate?integrated_account_id=${accountId}&limit=100`,
  {
    headers: {
      'Authorization': `Bearer ${process.env.TRUTO_API_KEY}`,
      'x-truto-disable-cache': 'true'
    }
  }
);

const { result, next_cursor } = await response.json();

// result is normalized regardless of provider
for (const candidate of result) {
  await db.candidates.upsert({
    externalId: candidate.id,
    firstName: candidate.first_name,
    lastName: candidate.last_name,
    email: candidate.primary_email
  });
}
```

The payoff is architectural. You write the loop once. Greenhouse pagination uses `Link` headers, Lever uses cursor offsets, and Workable uses page numbers. None of that leaks into your code—the unified API handles the complexity and returns a consistent `next_cursor`.

> [!WARNING]
> **Be honest about the limits of normalization.** No unified schema captures every custom field every ATS supports. Ashby has structured hiring plans, Greenhouse has custom application fields, and Lever has nested tags. Truto's architecture allows for environment-level overrides. You can inject custom JSONata logic to map those specific native fields into the unified response without waiting for a vendor to update their core schema.

## Step 2: Dropping in the Link SDK

With the unified data model understood, we can embed the Link UI into our frontend application. Three steps get it working.

### Generate a Link Token on Your Backend

Never expose your platform API key in the browser. First, your backend must generate a short-lived Link Token for the current user. This ensures the frontend cannot spoof connection requests for other tenants.

```typescript
// Server-side: Node.js / Express
app.post('/api/integrations/link-token', async (req, res) => {
  const { tenantId } = req.user;
  const response = await fetch('https://api.truto.one/link-token', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${process.env.TRUTO_API_KEY}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      tenant_id: tenantId,
      integrations: ['greenhouse', 'lever', 'workable', 'ashby'],
      unified_model: 'ats'
    })
  });
  
  const data = await response.json();
  res.json({ link_token: data.link_token });
});
```

### Mount the SDK in Your Frontend

Next, install the Link SDK in your frontend application and initialize it with the token. This example uses React, but the vanilla JavaScript implementation is nearly identical.

```tsx
// Frontend: React
import { useState } from 'react';
import { TrutoLink } from '@truto/link-react';

export default function IntegrationsPage() {
  const [linkToken, setLinkToken] = useState<string | null>(null);

  const handleConnect = async () => {
    const response = await fetch('/api/integrations/link-token', { method: 'POST' });
    const data = await response.json();
    setLinkToken(data.link_token);
  };

  const handleSuccess = ({ integratedAccountId, integration }) => {
    console.log('Connected to ATS:', integration);
    console.log('Account ID:', integratedAccountId);
    // Save the integratedAccountId to your database against the tenant
  };

  return (
    <div>
      <h2>Applicant Tracking Systems</h2>
      <button onClick={handleConnect}>Connect your ATS</button>

      {linkToken && (
        <TrutoLink
          token={linkToken}
          onSuccess={handleSuccess}
          onClose={() => setLinkToken(null)}
        />
      )}
    </div>
  );
}
```

### The Proactive Token Refresh Lifecycle

When a user successfully connects their ATS, the Link UI returns an `integrated_account_id`. This ID is all you need to make API calls—you never handle the actual OAuth tokens.

Behind the scenes, the integration platform handles the entire OAuth 2.0 authorization code flow, including PKCE validation. More importantly, it quietly saves the most engineering hours by handling proactive token refreshes.

OAuth tokens expire. Relying on reactive refreshes (waiting for an API call to fail with a 401 Unauthorized, then refreshing) leads to race conditions and dropped requests in highly concurrent systems. Truto solves this proactively. Before every API call, the platform checks if the token is expired using a 30-second buffer. If it is within the buffer, it refreshes the token before forwarding the request.

Additionally, the platform schedules work ahead of token expiry, refreshing credentials 60 to 180 seconds before they expire. If a refresh fails (e.g., the user revoked access in Greenhouse, or rotated credentials in Lever), the integrated account is marked as `needs_reauth` and an `integrated_account:authentication_error` webhook is fired. Your application can listen for this webhook and prompt the user to re-open the Link UI to restore the connection.

## Step 3: Handling Rate Limits and Webhooks

This is where most teams get burned. Every ATS rate-limits differently. Greenhouse Harvest allows 50 requests per 10 seconds. Lever caps at 10 requests per second. Workable bursts at 60 per minute. If you wrote a naive sync loop, you would build five different backoff strategies.

### Transparent Rate Limit Handling

One of the most dangerous anti-patterns in unified API platforms is the silent absorption of rate limits. Some platforms attempt to automatically retry requests when an upstream provider returns an HTTP 429 Too Many Requests error. This creates a massive backlog of queued requests, leading to unpredictable latency spikes and eventual system failure.

Truto does **not** silently retry, throttle, or apply backoff on rate limit errors. When an upstream ATS API returns an HTTP 429, Truto passes that error directly back to your application. Hiding 429s causes worse outages than surfacing them—your code loses observability into provider health, and retry storms can compound across customers.

To make this predictable, Truto normalizes upstream rate limit information into standardized IETF headers, regardless of what the upstream provider uses:
*   `ratelimit-limit`: The total number of requests allowed in the current window.
*   `ratelimit-remaining`: The number of requests left in the current window.
*   `ratelimit-reset`: The timestamp (or seconds remaining) when the rate limit window resets.

Your application is responsible for implementing proper exponential backoff with jitter based on these headers:

```typescript
async function fetchCandidatesWithBackoff(integratedAccountId: string, attempt = 0): Promise<any> {
  const response = await fetch(`https://api.truto.one/unified/ats/candidates?integrated_account_id=${integratedAccountId}`, {
    headers: {
      'Authorization': `Bearer ${process.env.TRUTO_API_KEY}`
    }
  });

  if (response.status === 429) {
    const resetTime = parseInt(response.headers.get('ratelimit-reset') || '5', 10);
    // Calculate delay based on reset time, adding jitter to prevent thundering herds
    const delayMs = (resetTime * 1000) + (Math.random() * 1000);
    
    console.warn(`Rate limit hit. Backing off for ${delayMs}ms`);
    await new Promise(resolve => setTimeout(resolve, delayMs));
    
    if (attempt < 4) {
      return fetchCandidatesWithBackoff(integratedAccountId, attempt + 1);
    }
    throw new Error('Rate limit exceeded after maximum retries');
  }

  return response.json();
}
```

### Normalized Webhook Delivery

Polling an ATS for new candidates every five minutes scales poorly past a few hundred customers and burns through rate limits quickly. [Webhooks are essential for real-time synchronization](https://truto.one/blog/developer-quickstart-link-ui-unified-webhooks-for-b2b-saas/). However, every ATS formats their webhooks differently. Lever might send a `candidate.stage_change` event, while Workable sends `application_moved`.

Truto handles incoming webhooks from third-party integrations, verifies their cryptographic signatures, and maps the proprietary event payload into a standardized unified webhook event. You only verify Truto's signature once.

When a candidate is moved to a new stage in any supported ATS, your application receives a single, normalized `ats.application.updated` or `ats.candidate.created` event containing the unified object. You only need to build one webhook handler to support real-time updates across your entire integration catalog.

```typescript
// Server-side Webhook Receiver
app.post('/webhooks/truto', verifyTrutoSignature, async (req, res) => {
  const { event_type, integrated_account_id, data } = req.body;
  
  switch (event_type) {
    case 'ats.candidate.created':
      await ingestCandidate(integrated_account_id, data);
      break;
    case 'integrated_account:authentication_error':
      await notifyUserToReconnect(integrated_account_id);
      break;
  }
  
  res.status(200).end();
});
```

## Auth Patterns: How Greenhouse, Lever, and Workable Differ

The reason multi-ATS integration takes months is that each provider implements authentication differently. If you are building natively, here is the matrix you have to implement and maintain:

| Aspect | Greenhouse (Harvest) | Lever | Workable |
|---|---|---|---|
| Partner Auth | OAuth 2.0 Auth Code | OAuth 2.0 Auth Code | OAuth 2.0 Auth Code |
| Internal/Custom Auth | Basic Auth (API key as username, blank password) | Basic Auth (API key as username, blank password) | Bearer token (access token) |
| Token Expiry | 1h access / 24h refresh | 1h (3600s) | Varies by grant |
| Special Requirement | `On-Behalf-Of` header with user ID | `audience` parameter in authorize URL | Subdomain in base URL |
| Rate Limit | 50 req / 10s (Harvest v1/v2) | 10 req/s steady, 2 req/s for POSTs | ~60 req / min |
| Pagination Style | Link headers (RFC-5988) | Offset token cursor + `hasNext` | Page-based |

<cite index="3-4">Greenhouse's Harvest V3 API uses the standard OAuth 2.0 Authorization Code Grant flow</cite>, but it comes with Greenhouse-specific requirements. <cite index="3-26,3-27,3-28">Access tokens expire after 1 hour, and the refresh token lasts 24 hours - if the refresh token expires unused, the user must repeat the entire authorization flow.</cite> That 24-hour refresh window is a trap. If your sync job runs weekly, every single Greenhouse connection will break on Monday morning.

<cite index="18-13,18-14">For Lever, OAuth 2.0 is mandatory for partner integrations. Lever's implementation follows the standard Authorization Code Grant flow, but with Lever-specific requirements that trip up developers</cite> - including a required `audience` parameter and separate sandbox/production environments with different auth servers.

<cite index="28-6,28-7">Workable's official partners access API endpoints through OAuth 2.0 using the Authorization Code flow, where the partner must be authorized beforehand by Workable to receive a `client_id` and `client_secret`.</cite> Workable also requires the customer's subdomain to construct the correct base URL for API requests.

Here is what a native Greenhouse OAuth token exchange looks like if you are building from scratch:

```typescript
// Native Greenhouse OAuth - you'd have to build this for each provider
async function exchangeGreenhouseCode(code: string): Promise<TokenResponse> {
  const response = await fetch('https://api.greenhouse.io/oauth/token', {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: new URLSearchParams({
      grant_type: 'authorization_code',
      code,
      client_id: process.env.GREENHOUSE_CLIENT_ID!,
      client_secret: process.env.GREENHOUSE_CLIENT_SECRET!,
      redirect_uri: process.env.GREENHOUSE_REDIRECT_URI!
    })
  });
  return response.json();
}

// Then you'd write a nearly identical function for Lever...
async function exchangeLeverCode(code: string): Promise<TokenResponse> {
  const response = await fetch('https://auth.lever.co/oauth/token', {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: new URLSearchParams({
      grant_type: 'authorization_code',
      code,
      client_id: process.env.LEVER_CLIENT_ID!,
      client_secret: process.env.LEVER_CLIENT_SECRET!,
      redirect_uri: process.env.LEVER_REDIRECT_URI!
    })
  });
  return response.json();
}

// ...and another for Workable, with a subdomain requirement
```

That's three OAuth implementations before you've written a single line of business logic. Each one needs its own token storage, refresh scheduling, error handling, and re-auth flow.

With the unified approach, your code never touches OAuth. You call the Link UI, get back an `integrated_account_id`, and make API calls. The platform handles credential resolution through a hierarchy - base OAuth config at the integration level, overrides at the environment level, and per-account overrides when needed. It figures out whether the account uses OAuth 2.0 authorization code, client credentials, or API key auth and applies the right strategy.

> [!TIP]
> **Test case: Token expiry across providers.** After connecting test accounts for all three providers, wait 90 minutes and make an API call to each. Verify that the unified API returns fresh data without a 401. This confirms that proactive token refresh is working for Greenhouse (1h expiry), Lever (1h expiry), and Workable.

## Pagination Translation: From Link Headers to a Unified Cursor

Every ATS paginates differently. This is one of the most tedious aspects of multi-provider integration, and getting it wrong means missing candidate records or duplicating them.

### What Each Provider Returns Natively

**Greenhouse** uses RFC-5988 Link headers. <cite index="32-14,32-15">Paginated results include a Link response header</cite> that looks like this:

```
HTTP/1.1 200 OK
Link: <https://harvest.greenhouse.io/v1/candidates?page=2&per_page=100>; rel="next",
      <https://harvest.greenhouse.io/v1/candidates?page=47&per_page=100>; rel="last"
X-RateLimit-Limit: 50
X-RateLimit-Remaining: 49
```

<cite index="36-3">Harvest v3 uses cursor-based pagination for list endpoints.</cite> <cite index="36-17">Passing a cursor with any other query params returns a 422 error</cite> - the cursor must be the only parameter on subsequent requests.

**Lever** returns cursor data in the JSON response body. <cite index="42-6,42-7,42-8,42-9">Lever uses cursor-based pagination with list endpoints returning a `next` cursor token and a `hasNext` boolean, with configurable page size between 1 and 100 items.</cite>

```json
{
  "data": [
    { "id": "abc-123", "name": "Jane Doe", "stage": "interview" }
  ],
  "hasNext": true,
  "next": "1686268200000_abc-124"
}
```

**Workable** uses classic page-number pagination with a `paging` object in the response body.

### The Unified Cursor Interface

Instead of writing three different pagination parsers, every unified API response returns the same structure:

```json
{
  "result": [
    { "id": "12345", "first_name": "Jane", "last_name": "Doe" }
  ],
  "next_cursor": "eyJwYWdlIjoyLCJwZXJfcGFnZSI6MTAwfQ=="
}
```

When `next_cursor` is `null`, you have reached the last page. Here is a complete paginated sync that works identically across Greenhouse, Lever, and Workable:

```typescript
async function syncAllCandidates(integratedAccountId: string): Promise<void> {
  let cursor: string | null = null;
  let totalSynced = 0;

  do {
    const url = new URL('https://api.truto.one/unified/ats/candidates');
    url.searchParams.set('integrated_account_id', integratedAccountId);
    url.searchParams.set('limit', '100');
    if (cursor) {
      url.searchParams.set('cursor', cursor);
    }

    const response = await fetch(url.toString(), {
      headers: { 'Authorization': `Bearer ${process.env.TRUTO_API_KEY}` }
    });

    if (response.status === 429) {
      const resetSeconds = parseInt(response.headers.get('ratelimit-reset') || '5', 10);
      await new Promise(resolve => setTimeout(resolve, resetSeconds * 1000 + Math.random() * 1000));
      continue; // retry the same page
    }

    if (!response.ok) {
      throw new Error(`Sync failed: ${response.status} ${response.statusText}`);
    }

    const { result, next_cursor } = await response.json();

    for (const candidate of result) {
      await db.candidates.upsert({
        externalId: candidate.id,
        integratedAccountId,
        firstName: candidate.first_name,
        lastName: candidate.last_name,
        email: candidate.primary_email,
        lastSyncedAt: new Date()
      });
    }

    totalSynced += result.length;
    cursor = next_cursor;
  } while (cursor);

  console.log(`Synced ${totalSynced} candidates for account ${integratedAccountId}`);
}
```

Behind the scenes, the platform translates Greenhouse's Link header URLs into cursors, extracts Lever's `next` offset token, and converts Workable's page numbers. Your code never parses a `Link` header or checks `hasNext`.

## Verifying Webhook Signatures

Every ATS signs their webhooks differently. <cite index="13-17,13-18">Lever signs webhook requests and includes the signature within the body of the POST request, with a signature parameter included if a signing token has been generated.</cite> Greenhouse uses a different HMAC format. Workable has its own scheme.

With a unified webhook pipeline, you verify one signature - Truto's. The platform receives the native webhook from the ATS, verifies the provider's cryptographic signature using timing-safe comparison, maps the event to the unified schema, and re-signs the payload before delivering it to your endpoint.

Here is a complete verification implementation using `X-Truto-Signature`:

```typescript
import crypto from 'crypto';

function verifyTrutoSignature(
  req: Request,
  res: Response,
  next: NextFunction
): void {
  const signature = req.headers['x-truto-signature'] as string;
  const webhookSecret = process.env.TRUTO_WEBHOOK_SECRET!;

  if (!signature) {
    res.status(401).json({ error: 'Missing signature header' });
    return;
  }

  const rawBody = (req as any).rawBody; // requires raw body middleware
  const expectedSignature = crypto
    .createHmac('sha256', webhookSecret)
    .update(rawBody)
    .digest('hex');

  // Timing-safe comparison to prevent side-channel attacks
  const isValid = crypto.timingSafeEqual(
    Buffer.from(signature),
    Buffer.from(expectedSignature)
  );

  if (!isValid) {
    res.status(401).json({ error: 'Invalid signature' });
    return;
  }

  next();
}
```

> [!WARNING]
> **You must use timing-safe comparison.** A naive string equality check (`===`) leaks information about which bytes of the signature are correct, making it vulnerable to timing attacks. Always use `crypto.timingSafeEqual` or your language's equivalent.

For your retry strategy, respond with a `200 OK` as quickly as possible. If your webhook handler needs to do slow work (database writes, downstream API calls), acknowledge the webhook first and process asynchronously:

```typescript
app.post('/webhooks/truto', verifyTrutoSignature, async (req, res) => {
  // Acknowledge immediately
  res.status(200).end();

  // Process asynchronously
  try {
    const { event_type, integrated_account_id, data } = req.body;
    await processWebhookEvent(event_type, integrated_account_id, data);
  } catch (err) {
    console.error('Webhook processing failed:', err);
    // Queue for retry in your own system
    await retryQueue.enqueue(req.body);
  }
});
```

## Building a Reconciliation Job

Webhooks handle real-time updates, but they are not a complete data strategy. Webhooks can be missed due to network issues, your endpoint being temporarily down, or provider-side delivery failures. A periodic reconciliation job fills the gaps.

This pattern runs on a schedule (every 6-12 hours), fetches records updated since the last sync, and upserts them into your database. It acts as a safety net for any events your webhook handler missed.

```typescript
interface SyncState {
  integratedAccountId: string;
  lastSyncedAt: string; // ISO-8601 timestamp
}

async function reconcileCandidates(state: SyncState): Promise<SyncState> {
  let cursor: string | null = null;
  let recordsProcessed = 0;
  const syncStartedAt = new Date().toISOString();

  do {
    const url = new URL('https://api.truto.one/unified/ats/candidates');
    url.searchParams.set('integrated_account_id', state.integratedAccountId);
    url.searchParams.set('limit', '100');
    url.searchParams.set('updated_after', state.lastSyncedAt);
    if (cursor) {
      url.searchParams.set('cursor', cursor);
    }

    const response = await fetch(url.toString(), {
      headers: { 'Authorization': `Bearer ${process.env.TRUTO_API_KEY}` }
    });

    if (response.status === 429) {
      const resetSeconds = parseInt(
        response.headers.get('ratelimit-reset') || '10', 10
      );
      await new Promise(r => setTimeout(r, (resetSeconds + 1) * 1000));
      continue;
    }

    if (!response.ok) {
      throw new Error(`Reconciliation failed: ${response.status}`);
    }

    const { result, next_cursor } = await response.json();

    for (const candidate of result) {
      await db.candidates.upsert({
        externalId: candidate.id,
        integratedAccountId: state.integratedAccountId,
        firstName: candidate.first_name,
        lastName: candidate.last_name,
        email: candidate.primary_email,
        rawPayload: candidate, // store for debugging
        lastSyncedAt: new Date()
      });
      recordsProcessed++;
    }

    cursor = next_cursor;
  } while (cursor);

  console.log(`Reconciliation complete: ${recordsProcessed} records for ${state.integratedAccountId}`);

  return {
    ...state,
    lastSyncedAt: syncStartedAt
  };
}

// Run for all connected accounts
async function runFullReconciliation(): Promise<void> {
  const accounts = await db.integratedAccounts.findAll({ status: 'active' });

  for (const account of accounts) {
    try {
      const state = await db.syncState.findOne(account.id) || {
        integratedAccountId: account.id,
        lastSyncedAt: new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString()
      };
      const newState = await reconcileCandidates(state);
      await db.syncState.upsert(newState);
    } catch (err) {
      console.error(`Reconciliation failed for ${account.id}:`, err);
      // Continue with next account - don't let one failure block others
    }
  }
}
```

> [!TIP]
> **Test cases for your reconciliation job:**
> 1. **Happy path:** Connect a test account, create a candidate in the ATS UI, run the job, verify the record appears in your database.
> 2. **Idempotency:** Run the job twice in a row. Confirm no duplicate records are created (the upsert should update, not insert).
> 3. **Rate limit handling:** Set `limit=1` to force many pages and trigger rate limits faster. Verify the job completes without crashing.
> 4. **Stale token:** Revoke the OAuth token in the ATS provider's UI, then run the job. Verify your system receives the `integrated_account:authentication_error` webhook and marks the account for re-auth instead of silently failing.
> 5. **Empty response:** Run against an ATS with no candidates. Verify the job completes with `0 records` and updates the sync timestamp.

## Debugging and Monitoring Multi-ATS Integrations

Once you are in production with multiple ATS providers, these are the issues that will wake you up at 3am.

### Common Failure Scenarios

**"401 Unauthorized from Greenhouse after the weekend."** <cite index="3-28">If the refresh token is not used within 24 hours, the user must repeat the entire authorization flow.</cite> This catches teams who rely on weekly sync jobs. The fix: proactive token refresh on a schedule, well before the 24-hour refresh window. Truto handles this by refreshing credentials 60-180 seconds before expiry and scheduling follow-up refreshes immediately after each successful token rotation.

**"Lever returns 429 on bulk candidate import."** <cite index="41-9,41-10">Lever enforces a steady-state rate limit of 10 requests per second per API key, with burst capacity up to 20. Application POST requests have a stricter limit of just 2 requests per second.</cite> If you are creating candidates in bulk through the unified API, you need to pace your writes to respect that 2 req/s POST ceiling. Check the `ratelimit-remaining` header after each write and back off proactively when it drops below 2.

**"Greenhouse API returns 403 on list endpoints."** <cite index="3-34,3-35">All list endpoints require authorization by a Greenhouse user with Site Admin privileges. If a non-Site Admin authorized the connection, attempts to access these endpoints will result in a 403.</cite> This is a permissions issue, not an auth issue. Your Link UI should document the required permission level during the connection flow.

**"Webhook events arriving but data looks stale."** This typically means your webhook handler is processing events but the underlying API call to fetch the full record is hitting a cached or stale response. Always pass `x-truto-disable-cache: true` on reads triggered by webhook events to ensure fresh data.

**"Connection works for one customer but fails for another on the same provider."** Each ATS customer's account can have different permission configurations, custom fields, and API access levels. Use the `integrated_account_id` to isolate debugging. Make a direct API call for the failing account and inspect the error response - it usually reveals a missing permission or a deactivated user.

### Recommended Monitoring

Set up alerts on these signals:

*   **`integrated_account:authentication_error` webhook count** - a spike means tokens are failing to refresh across multiple customers. Investigate immediately.
*   **HTTP 429 response rate per provider** - track this over time to spot customers approaching rate limit ceilings. Consider staggering sync jobs.
*   **Reconciliation job duration and record count** - a sudden drop in records processed could indicate a silent auth failure or API change.
*   **Webhook delivery latency** - measure the time between your `200 OK` response and the completion of async processing. If this grows, your processing queue is backing up.
*   **`needs_reauth` account count** - this should be a small percentage of total connected accounts. If it creeps above 5%, something systemic is wrong with token refresh.

```typescript
// Example: simple monitoring for your reconciliation job
async function monitoredReconciliation(accountId: string): Promise<void> {
  const startTime = Date.now();
  const metrics = { recordsProcessed: 0, rateLimitHits: 0, errors: 0 };

  try {
    const state = await db.syncState.findOne(accountId);
    const result = await reconcileCandidates(state!);
    metrics.recordsProcessed = /* count from result */0;
  } catch (err) {
    metrics.errors++;
    throw err;
  } finally {
    const duration = Date.now() - startTime;
    await telemetry.record('reconciliation.completed', {
      accountId,
      durationMs: duration,
      ...metrics
    });

    if (duration > 300_000) { // 5 minutes
      await alerts.warn(`Reconciliation for ${accountId} took ${duration}ms`);
    }
  }
}
```

## Stop Building Custom Settings Pages

Your integrations directory is not a feature checkbox. It is a revenue page. If a prospect cannot find their specific ATS on your marketing site, you are functionally invisible to them during the evaluation phase.

The arithmetic that should drive your decision: every custom ATS settings page you build is roughly four to six weeks of senior engineering, plus 15-20% of that cost annually in maintenance, plus an unbounded amount of on-call time for token refresh failures and breaking API changes. Multiply by the number of ATSs your sales team needs to win deals, and you have an engineering org that ships nothing else.

By leveraging an embeddable Link UI and a declarative unified API, you flip this arithmetic. One frontend component, one backend endpoint, one webhook receiver. You bypass the need to build custom settings pages, bespoke OAuth flow handlers, and complex token refresh CRON jobs. Adding a new ATS to your supported list becomes a configuration change, allowing you to launch integrations with Greenhouse, Lever, Workable, Ashby, and dozens of other platforms in a matter of days, not quarters.

Stop punishing your senior engineers with API documentation for legacy recruiting platforms. Standardize your connection flows, normalize your data models, and unblock your sales pipeline.

> Ready to stop building bespoke ATS integrations? Talk to our engineering team about embedding a unified Link UI into your SaaS product today to handle custom fields, webhooks, and multi-ATS connections.
>
> [Talk to us](https://truto.one/book-a-demo/)
