Syncing with Tripletex in practice: pagination, rate limits, duplicates and retries

Najważniejsze wnioski:

  1. Page with from and count (default 1000) and stop when a page has fewer rows than count. fullResultSize is deprecated and not exact. One query can never return more than 10,000 results, so split large reads by date.

  2. changedSince exists only on /customer, /product, /supplier and /ledger/voucher/>nonPosted. Everything else needs date windows, webhooks or full scans.

  3. Webhooks are [BETA] and retried for 30 hours, then the subscription can be disabled. Always run a nightly reconciliation job and compare version numbers.

  4. The API allows 100 requests per 10 seconds per employee and integration. Wait for Retry-After on 429, back off with jitter, and never blindly retry a POST that may already have created something.

A reliable sync with Tripletex rests on five habits: page through lists with from and count and split big reads by date, because one query never returns more than 10,000 results; fetch only changes where the API supports it (changedSince, webhooks) and run a full reconciliation job anyway; look up before you create, so retries never make duplicates; respect the limit of 100 requests per 10 seconds with backoff; and log every request id. This guide shows each one in TypeScript for a Supabase Edge Function or Node server, for apps built with Lovable, Claude Code or Cursor.

It is part two. Part one covers tokens and sessions: Tripletex API for builders: authentication and session tokens. The code below reuses the cached tripletex() client from that guide. All API details come from the official OpenAPI spec (version 2.75.23) and the guides on developer.tripletex.no, as of November 2026. The code is based on the official API spec; test it against the Tripletex test environment before production.

How does pagination work in the Tripletex API?

List endpoints return an envelope: {fullResultSize, from, count, versionDigest, values[]}. You control paging with two query parameters:

  • from: the index of the first row (default 0).
  • count: how many rows per page (default 1000).

Stop when a page has fewer rows than you asked for. Do not loop on fullResultSize: the spec marks it [DEPRECATED] and says "the value is not exact". versionDigest is a hash of the full result, useful to check whether a list changed since your last read. Add sorting=id so pages come back in a stable order.

What is the 10,000 result limit, and how do you get around it?

One query can return at most 10,000 results. Above that, Tripletex answers with 422 "Result set too large. Limit of 10.000 reached." (code 23000). A smaller count does not help, because the limit applies to the query, not the page. Narrow the query instead, usually by date.

Several endpoints require a date range anyway:

  • GET /invoice: invoiceDateFrom (inclusive) and invoiceDateTo (exclusive). It returns charged outgoing invoices only.
  • GET /order: orderDateFrom and orderDateTo.
  • GET /ledger/voucher and GET /timesheet/entry: dateFrom and dateTo.
  • GET /supplierInvoice: invoiceDateFrom and invoiceDateTo.

Because the end date is exclusive on these endpoints, month windows (1 January to 1 February, 1 February to 1 March, and so on) never overlap and never leave a gap. If one month still passes 10,000 rows, split it into weeks.

How do you make responses smaller with fields?

By default, related objects come back as {id, url} only. The fields parameter chooses exactly what you get: fields=id,version,name,email, fields=*,orderLines(*) for everything plus the order lines, or customer(id,name) for part of a related object. Ask only for what you store. Smaller responses are faster, and you are less likely to copy data you don't need into your own database.

Always include version. Every persisted object has a revision number, and you will use it below to avoid overwriting newer data with older data.

A paging helper with rate limits and safe retries

The API allows 100 requests per 10 seconds, per employee and integration (several keys for the same employee and integration share one count). Responses carry X-Rate-Limit-Limit, X-Rate-Limit-Remaining and X-Rate-Limit-Reset (seconds left), and a 429 carries Retry-After. Tripletex asks you to read the headers rather than hard-code the numbers (rate limiting docs).

// supabase/functions/_shared/tripletex-sync.ts
// Based on the official API spec; test against the Tripletex test environment before production.
import { tripletex } from "./tripletex.ts"; // cached session client from part one

const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));

export async function callWithRetry(
  path: string,
  init: { method?: string; body?: string } = {},
  maxAttempts = 6,
): Promise<Response> {
  for (let attempt = 1; ; attempt++) {
    const res = await tripletex(path, init);

    // Slow down before hitting the limit.
    if (res.headers.get("X-Rate-Limit-Remaining") === "0") {
      await sleep(Number(res.headers.get("X-Rate-Limit-Reset") ?? 10) * 1000);
    }

    // 429: the request was rejected, so it is safe to send again.
    // 5xx: only retry reads. A POST may have succeeded before the error (see duplicates).
    const isRead = !init.method || init.method === "GET";
    const retry = res.status === 429 || (res.status >= 500 && isRead);
    if (!retry || attempt >= maxAttempts) return res;

    const retryAfter = Number(res.headers.get("Retry-After") ?? 0) * 1000;
    const backoff = Math.min(1000 * 2 ** attempt, 120_000);
    await sleep(Math.max(retryAfter, backoff) + Math.random() * 1000); // jitter
  }
}

export async function fetchAll<T>(path: string, params: Record<string, string>): Promise<T[]> {
  const count = 1000;
  const all: T[] = [];
  for (let from = 0; ; from += count) {
    const qs = new URLSearchParams({ sorting: "id", ...params, from: String(from), count: String(count) });
    const res = await callWithRetry(`${path}?${qs}`);
    if (!res.ok) {
      // The body has status, code, message, validationMessages and requestId.
      throw new Error(`${path} failed: ${res.status} ${await res.text()}`);
    }
    const page = await res.json();
    all.push(...page.values);
    if (page.values.length < count) return all; // fullResultSize is not exact
  }
}

Two rules matter more than the exact numbers:

  • Never retry other 4xx errors unchanged. 30 failed requests in a row (status 400 or above, excluding 429) to the same endpoint and method block that endpoint with 429 for 15, 30, 60, 75, 90 and up to 120 seconds. Read message and validationMessages, fix the data, then try again.
  • Some endpoints have their own limits. GET /ledger/posting with changes in fields is limited to 300 requests per 5 minutes.

Example: all invoices for 2026, one month at a time:

for (let m = 0; m < 12; m++) {
  const from = new Date(Date.UTC(2026, m, 1)).toISOString().slice(0, 10);
  const to = new Date(Date.UTC(2026, m + 1, 1)).toISOString().slice(0, 10); // exclusive
  const invoices = await fetchAll("/invoice", {
    invoiceDateFrom: from,
    invoiceDateTo: to,
    fields: "id,version,invoiceNumber,invoiceDate,amountOutstanding,customer(id,name)",
  });
  // upsert into your database here
}

When can you use changedSince, and when do you need a full scan?

The changedSince filter returns only rows changed after a timestamp. In the current spec it exists on four endpoints only:

  • GET /customer
  • GET /product (added in 2.75.13, October 2026)
  • GET /supplier
  • GET /ledger/voucher/>nonPosted

For orders, invoices, projects, hours and everything else, use date windows, webhooks or full scans. Details that trip people up:

  • The timestamp must be ISO 8601 with an offset, for example 2026-11-24T08:00:00+01:00. Without an offset you get 422. In a URL, + must be encoded as %2B (URLSearchParams does this for you).
  • Results may include changes from up to 10 minutes before your timestamp. That is fine if your upsert compares version.
  • For products, deleted rows are not returned. To notice deletions, use webhook .delete events or a periodic full scan that compares ids.
// Incremental customer sync. Save runStartedAt only after the run succeeds.
const runStartedAt = new Date().toISOString().replace("Z", "+00:00");
const changed = await fetchAll("/customer", {
  changedSince: lastSuccessfulRunStartedAt, // from your sync_runs table
  fields: "id,version,name,email,organizationNumber,isInactive",
});
// upsert each row only if its version is newer than the stored one

How do Tripletex webhooks work, and why do you still need a reconciliation job?

Tripletex calls them event subscriptions. The endpoints are tagged [BETA] in the spec, which means they "can be subject to change". You subscribe with POST /event/subscription; GET /event lists the available event keys. Events use the format object.verb, for example customer.create, customer.update, customer.delete, order.update, product.delete or invoice.charged, and each verb needs its own subscription. See the webhooks guide.

curl -s -u "0:$SESSION_TOKEN" -X POST "https://tripletex.no/v2/event/subscription" \
  -H "Content-Type: application/json" \
  -d '{
    "event": "customer.update",
    "targetUrl": "https://<project-ref>.supabase.co/functions/v1/tripletex-webhook",
    "fields": "id,version,name,email,organizationNumber",
    "authHeaderName": "x-webhook-secret",
    "authHeaderValue": "<long random string>"
  }'

The payload is {subscriptionId, event, id, value}; on delete events value is null. The docs recommend a custom auth header like the one above. The spec also describes optional HMAC signing: set hmacSharedSecret on the subscription, and each delivery carries x-request-signature = base64(HmacSHA512(idempotency-key header + "&" + body)).

Delivery is described as "guaranteed", with retries at increasing intervals over 30 hours. After a week of constant failure the subscription status becomes DISABLED_TOO_MANY_ERRORS, and you re-enable it with PUT /event/subscription/{id}. That is why webhooks alone are not enough:

  • If your endpoint is down for longer than the retry window, those events are gone.
  • A disabled subscription sends nothing, and nobody notices unless you check its status.
  • Not every object has events, and the list may change while the feature is in beta.
  • A bug in your handler can store an event without applying it correctly.

Tripletex's own advice: do a bulk sync after subscribing, compare version numbers, and run a nightly sync. Treat webhooks as the fast path and the nightly reconciliation job as the safety net.

A handler that answers fast and stores events for a worker to process (Supabase Edge Function; set verify_jwt = false for it in supabase/config.toml, because Tripletex does not send a Supabase user token):

// supabase/functions/tripletex-webhook/index.ts
// Based on the official API spec; test against the Tripletex test environment before production.
import { createClient } from "npm:@supabase/supabase-js@2";

const admin = createClient(
  Deno.env.get("SUPABASE_URL")!,
  Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!,
);

Deno.serve(async (req) => {
  if (req.headers.get("x-webhook-secret") !== Deno.env.get("TRIPLETEX_WEBHOOK_SECRET")) {
    return new Response("forbidden", { status: 403 });
  }
  const { subscriptionId, event, id, value } = JSON.parse(await req.text());

  // Store first, process later. delivery_key has a unique constraint,
  // so a redelivered event becomes a no-op.
  const { error } = await admin.from("tripletex_events").insert({
    delivery_key: req.headers.get("idempotency-key") ?? `${event}:${id}:${value?.version ?? "deleted"}`,
    subscription_id: subscriptionId,
    event,
    object_id: id,
    payload: value,
  });
  if (error && error.code !== "23505") {
    return new Response("try again", { status: 500 }); // Tripletex will retry
  }
  return new Response("ok", { status: 200 });
});

The worker that applies events, and the nightly job, both write through one upsert that ignores older versions:

create table public.tripletex_customers (
  tripletex_id bigint primary key,
  version int not null,
  name text,
  email text,
  organization_number text,
  deleted boolean not null default false
);
alter table public.tripletex_customers enable row level security; -- server writes only

create or replace function public.upsert_tripletex_customer(
  p_id bigint, p_version int, p_name text, p_email text, p_org text
) returns void language sql as $$
  insert into public.tripletex_customers (tripletex_id, version, name, email, organization_number)
  values (p_id, p_version, p_name, p_email, p_org)
  on conflict (tripletex_id) do update
    set version = excluded.version, name = excluded.name, email = excluded.email,
        organization_number = excluded.organization_number, deleted = false
    where public.tripletex_customers.version < excluded.version;
$$;

How do you avoid creating duplicates in Tripletex?

The Tripletex API does not document an idempotency key for creating objects (the idempotency-key header above belongs to webhook deliveries). If a POST /customer or POST /order times out, you do not know whether it was created. Retrying blindly is how duplicates are made. Patterns that work with what the API offers:

  • Keep a mapping table in your own database: your id, the Tripletex id, and a status. Before creating, set the status to creating in one atomic update, so two workers can't both create the same record. Save the Tripletex id from the response as soon as you get it.
  • Look up by a natural key before creating. GET /customer filters on organizationNumber, email and customerAccountNumber; GET /product on productNumber; GET /order on number and customerId (with the required date range); GET /invoice on invoiceNumber and kid. Note that isInactive defaults to false on /customer, so a lookup misses inactive customers unless you check them too.
  • After a timeout or 5xx on a POST, look up first, then decide. If you find exactly one match, store its id. If you find several, stop and alert a human.
  • Handle 409 responses: 7000 Object Exists and 14000 Duplicate entry mean "look it up, don't retry".
  • Send version on updates. If you include it in a PUT, Tripletex won't overwrite changes made since your GET; you get 409 with code 8000 (Revision) instead. Re-read, merge, try again.
  • Leave out id and version on POST, or you get "An ID cannot be set when creating a new object". Related objects are referenced by internal id, for example "customer": {"id": 123}.
// Based on the official API spec; test against the Tripletex test environment before production.
export async function findOrCreateCustomer(c: { name: string; organizationNumber: string; email?: string }) {
  const fields = "id,version,name,isInactive";
  const matches = [
    ...(await fetchAll<{ id: number }>("/customer", { organizationNumber: c.organizationNumber, fields })),
    ...(await fetchAll<{ id: number }>("/customer", { organizationNumber: c.organizationNumber, isInactive: "true", fields })),
  ];
  if (matches.length === 1) return matches[0].id;
  if (matches.length > 1) throw new Error(`Several Tripletex customers for ${c.organizationNumber}: needs a human`);

  const res = await callWithRetry("/customer", { method: "POST", body: JSON.stringify(c) });
  if (res.ok) return (await res.json()).value.id as number;
  // Timeout, 5xx or 409: it may exist now. Look up again before anything else.
  throw new Error(`Create customer failed: ${res.status} ${await res.text()}`);
}

Which system is the source of truth?

Decide this per object, and per field, before you write any sync code. A pattern that works for many apps:

  • Your app owns what users create in it: signups, orders as they are placed, project data your team edits in the app.
  • Tripletex owns everything accounting: invoice numbers, invoice status, payments, amountOutstanding, vouchers. Your app reads these and never edits them. GET /invoice/{id} returns amountOutstanding; above 0 means not fully paid.
  • Shared objects such as customers get one owner per field. If both sides can edit the same field, you need a written conflict rule, and version to detect conflicts.
  • Direction is explicit. One-way syncs are much easier to run than two-way. Start one-way, and add the other direction only for fields that need it.

What should you log, and when should someone get an alert?

  • Every request id. Each response has an x-tlx-request-id header, and error bodies include requestId. Store it with each failed call. It is what Tripletex support asks for.
  • A sync_runs table: started, finished, what was read and written, how many errors, and the timestamp you will use as the next changedSince.
  • Alert on: a run that didn't finish; repeated 401 or 429; any 403; webhook subscriptions whose status is not ACTIVE (check GET /event/subscription daily); a growing backlog of unprocessed events; and reconciliation finding rows that differ.
  • Never log tokens or full payloads with personal data. Log ids, versions and status codes.

For the full go-live list, see Before you switch on an integration in production: a checklist.

Brief for your AI coding tool

Paste this into Lovable, Claude Code or Cursor, after the authentication brief from part one:

Build a Tripletex sync on top of our existing server-side Tripletex client.

Reads:
- Page with from/count (count 1000, sorting=id). Stop when a page has fewer than count rows.
  Do not use fullResultSize (deprecated, not exact).
- One query returns at most 10,000 results (422, code 23000). Split by month using the
  required date filters (invoiceDateFrom/invoiceDateTo, orderDateFrom/orderDateTo,
  dateFrom/dateTo; the "To" date is exclusive).
- Always pass fields= with only the fields we store, and always include id and version.
- Use changedSince only on /customer, /product, /supplier. ISO 8601 with offset,
  URL-encoded. Expect overlap; upsert only if version is newer.

Webhooks:
- Subscribe via POST /event/subscription with authHeaderName/authHeaderValue.
- Edge Function "tripletex-webhook" (verify_jwt = false): check the auth header, insert the
  event into tripletex_events with a unique delivery_key (idempotency-key header), return 200
  fast. A separate worker applies events with a version-checked upsert.
- A nightly reconciliation job re-reads everything and fixes differences. Check daily that
  every subscription has status ACTIVE.

Writes:
- Never retry a POST blindly. Before creating, look up by natural key (organizationNumber,
  email, productNumber). After a timeout/5xx/409, look up again. Several matches = alert.
- Send version on PUT. On 409 code 8000, re-read and merge.

Limits and errors:
- 100 requests per 10 s. Read X-Rate-Limit-Remaining/Reset. On 429 wait Retry-After, then
  exponential backoff with jitter. Never retry other 4xx unchanged (30 failures in a row
  block the endpoint).
- Log x-tlx-request-id, status, code, message for every failure. Never log tokens.
- Keep a sync_runs table and tell me which alerts to set up.

When to bring in a developer

A one-way read sync of customers or invoices is a good project to build yourself with the patterns above. Bring in an experienced developer when:

  • The sync is two-way, or both systems can edit the same fields.
  • Your app creates invoices, vouchers or payments in Tripletex, where a duplicate is a real accounting problem.
  • Volumes are large: many customers, many Tripletex companies, or history beyond 10,000 rows per period.
  • You can't answer: what happens if the webhook endpoint is down for two days, and how would we find out?
  • The code works in the test environment, but nobody has reviewed how it behaves on errors and retries.

We build and take over this kind of integration: connecting vibe-coded apps to real systems, Tripletex integrations, and a code audit of what your AI tool wrote. One example from our work is a ClickUp and Tripletex integration. For the wider picture, read Connecting a vibe-coded app to real systems. Rocksoft is a software company with teams in Poland and Norwegian-speaking staff, building integrations and custom software for companies in Norway and across Europe.

Related guides

FAQ

How many rows can I get from the Tripletex API in one request?

count defaults to 1000 per page. One query, across all its pages, can return at most 10,000 results; beyond that you get "Result set too large". Split the query by date.

Can I rely on fullResultSize to know how many pages there are?

No. The spec marks it deprecated and says the value is not exact. Keep paging until a page has fewer rows than count.

Which Tripletex endpoints support changedSince?

In the current spec: /customer, /product, /supplier and /ledger/voucher/>nonPosted. For other data, use date filters, webhooks or full scans.

If I use webhooks, do I still need a scheduled sync?

Yes. Webhooks are in beta, retries stop after 30 hours, and a subscription can be disabled after repeated failures. Tripletex itself recommends a nightly sync next to webhooks.

What is the Tripletex API rate limit?

100 requests per 10 seconds, per employee and integration. Creating session tokens has its own limit (180 per minute today, planned to drop toward about 10). Read the X-Rate-Limit-* headers rather than hard-coding these numbers.

Does Tripletex support idempotency keys for creating invoices or customers?

The API spec does not document one for creating objects. Prevent duplicates yourself: a mapping table, a lookup by natural key before each create, and a lookup instead of a blind retry after a timeout.