Guides

Integration Best Practices

Rate limiting, caching, error handling, and polling strategies

No Pagination#

List endpoints (listGrants, getAllWallets, etc.) return all results in a single response. There are no limit, offset, or cursor parameters.

Implications:

  • Cache responses locally and refresh periodically
  • Don't call list endpoints on every page load in your UI
  • For large organizations (1000+ grants), responses may be several MB

The examples use the tokuAPI helper from Build a Dashboard, which returns the data field of each response and throws on an error.

// Good: cache and refresh every 5 minutes
let grantCache = [];
let lastFetch = 0;

async function getGrants() {
  if (Date.now() - lastFetch > 5 * 60 * 1000) {
    grantCache = await tokuAPI('GET', 'listGrants');
    lastFetch = Date.now();
  }
  return grantCache;
}

Rate Limiting#

By default the API allows 300 requests per minute for the seat your token acts as and 600 requests per minute per IP address, plus at most 200 requests per second from one IP address. Over the limit you get 429 with a Retry-After header (in seconds).

Strategy:

  • Batch operations where possible (batchUpdateRoleInOrg, bulkUploadMultipleWallets, terminateEmployeeGrants)
  • Space out polling intervals (5-15 minutes, not seconds)
  • On 429, wait for Retry-After, then back off exponentially
async function tokuAPIWithRetry(method: string, endpoint: string, body?: any, retries = 3) {
  let lastMessage: string | undefined;
  for (let attempt = 0; attempt < retries; attempt++) {
    const last = attempt === retries - 1;
    const res = await fetch(`${TOKU_BASE_URL}/${endpoint}`, {
      method, headers, body: body ? JSON.stringify(body) : undefined
    });
    // A proxy in front of the API can answer with an HTML or empty body.
    const json = await res.json().catch(() => null);
    const error = json?.error;
    const message: string | undefined = typeof error === 'string' ? error : error?.message;

    if (res.status === 429 && !last) {
      const retryAfter = Number(res.headers.get('Retry-After') ?? 1);
      const waitMs = Math.max(retryAfter * 1000, Math.pow(2, attempt) * 1000);
      await new Promise(r => setTimeout(r, waitMs));
      continue;
    }

    // A 5xx can be a passing failure or a request that failed validation, and both
    // can answer { "error": { "message": "..." } }. Retry reads only, and stop when the
    // same message comes back twice: then the request needs fixing.
    const sameAsBefore = attempt > 0 && message !== undefined && message === lastMessage;
    if (res.status >= 500 && method === 'GET' && !sameAsBefore && !last) {
      lastMessage = message;
      const waitMs = Math.pow(2, attempt) * 2000;
      await new Promise(r => setTimeout(r, waitMs));
      continue;
    }

    if (!res.ok) throw new Error(`${res.status}: ${message ?? res.statusText}`);
    return json?.data;
  }
  throw new Error('Max retries exceeded');
}

Token Refresh#

API tokens expire after 30 days. After refresh, your newest working token keeps working for at most 7 more days. Refreshing needs a CLIENT_ORG_ADMIN token and always refreshes your own token; the body is optional.

// Refresh before expiry
const { personalToken } = await tokuAPI('POST', 'refreshUserApiToken', {});

// Store the new token
const newToken = personalToken.token;
const expiresAt = personalToken.expiresAt;

Set a calendar reminder or cron job to refresh 7 days before expiry. The old token continues working for 7 days after refresh, so there's no downtime during rotation.


Error Handling#

An operation that refuses a request answers { "error": { "message": "..." } }. Refusals from before the operation runs (bad token, unknown endpoint, rate limit) answer { "error": "..." } with a plain string. See Errors.

Don't retry these (fix the request):#

  • 400 Bad Request — invalid parameters
  • 401 Unauthorized — token expired or invalid, or no seat with the x-role-type role
  • 403 Forbidden — wrong role for this endpoint
  • 404 Not Found — resource or endpoint doesn't exist
  • 409 Conflict — the record already exists

Retry these (with backoff):#

  • 429 Too Many Requests — rate limited
  • 500 on a read — it can be a passing server failure, but requests that fail validation also return 500 with an error.message, so stop when the same message comes back

Before retrying a write that returned 500, check whether it already took effect (for example with listGrants after addSingleGrant), so a retry doesn't create it twice.

Common error patterns:#

try {
  const result = await tokuAPI('POST', 'terminateEmployeeGrants', {
    externalEmployeeID: 'EMP-001',
    terminationDate: '2026-06-30T00:00:00.000Z'
  });
  // Grants that were already terminated are listed, not treated as errors
  console.log(result.alreadyTerminatedGrantIDs);
} catch (err) {
  if (err.message.includes('No active employee found')) {
    // No active seat with that externalEmployeeID — check the ID
  } else {
    throw err; // Unexpected error
  }
}

Idempotency#

OperationIdempotent?Notes
listGrants, getAllWallets, etc.YesGET requests are always safe to retry
terminateGrantYesCalling it again succeeds and sets the termination date you send
terminateEmployeeGrantsYesGrants already terminated come back in alreadyTerminatedGrantIDs
addSingleGrantNoCreates a new grant each time — use unique names to detect duplicates
createUserRoleInOrgNoAn email that already has a recipient seat returns 409
approveWalletRequestPartiallyApproving a wallet that is no longer pending returns an error

Polling Strategy#

Without webhooks, poll for changes at appropriate intervals:

DataEndpointIntervalReason
Grant statuslistGrants5 minVesting events happen on schedule
Wallets waiting for a test transactiongetPendingWalletRequests2 minNew wallets need a test transaction
Wallet test txnsgetPendingWalletTestRequests2 minTest sent, waiting for confirmation
Org configurationgetOrgWalletInfo30 minRarely changes
Networks/tokensgetNetworksNew1 hourRarely changes

External Employee ID#

Always set externalEmployeeID when creating recipients. This is your primary key for correlating Toku data with your HRIS:

// Create with external ID
await tokuAPI('POST', 'createUserRoleInOrg', {
  email: 'jane@company.com',
  givenName: 'Jane',
  familyName: 'Smith',
  externalEmployeeID: 'EMP-001'  // Your system's ID
});

// Later, look up by external ID
const grants = await tokuAPI('GET',
  'getEmployeeGrants?externalEmployeeID=EMP-001'
);

// Terminate by external ID
await tokuAPI('POST', 'terminateEmployeeGrants', {
  externalEmployeeID: 'EMP-001',
  terminationDate: '2026-06-30T00:00:00.000Z'
});

Multi-Organization#

Each API token is scoped to one organization. If you manage multiple orgs, you need a separate token for each. Token scoping is enforced server-side — a token for Org A cannot access Org B's data.

Was this page helpful? Suggest edits