API Reference
Sending data reliably
How the SDK sends signals — buffered by default, with retries, idempotency, and the flush() you must call before a serverless function exits.
This page is about the @clocknext/sdk client. If you post to
the /api/v1/signal/* endpoints over raw HTTP, none of
the buffering below applies — each call is its own request, and retries,
batching, and idempotency are yours to implement. The answer is always 202
with the signal's signalId, never a priced result — see the endpoint's own
docs.
The client is async by default: signals.* buffers the signal in memory and
returns immediately. In a serverless function you must await cnk.flush()
before returning, or signals still in the buffer are lost when the process
freezes.
Async by default
Client-side only. cnk.signals.* doesn't send a request — it queues the
signal in memory and returns immediately:
// returns { status: "buffered", queued: true } instantly — nothing sent yet
cnk.signals.credit({
customerId: "cus_abc123",
model: "gpt-4o",
agentKey: "pro_credit",
tokens: { input: 1200, output: 480 },
});A background timer flushes the queue when either fires first:
batch.maxSizesignals queued (default 20)batch.maxIntervalMselapsed (default 2000 ms)
Each flush sends up to batch.maxConcurrency requests in parallel (default
5) — one POST /api/v1/signal/* request per signal, no bulk endpoint.
A failed request (a bad API key, a 400, the host unreachable) can't throw
back to your call — it already returned. Catch it via onError or flush().
Need the answer inline? Use { wait: true } or sync mode.
Wait for the signal's id
Await the send to get the signal's signalId back, or to catch a failed
request. The answer is never a price: the signal is checked and priced after
the 202. Per call:
const res = await cnk.signals.credit(
{ customerId: "cus_abc123", model: "gpt-4o", agentKey: "pro_credit", tokens: { input: 1200, output: 480 } },
{ wait: true },
);
res.status; // "accepted"
res.signalId; // find it with cnk.signals.list() or cnk.signals.lookupUsageLogs()A signal that can't be counted (an unknown agentKey, no active plan, …) never
reaches onError: it is kept as PENDING with its error. List those with
cnk.signals.list({ status: "PENDING" }),
fix the cause, and send them again with
cnk.signals.retry(ids).
…or globally, so every call awaits its send:
const cnk = new ClockNext({ apiKey: process.env.CLOCKNEXT_API_KEY!, mode: "sync" });Flush before you exit
Drain the buffer at these boundaries:
// Before a serverless function returns (Lambda, Vercel, Cloud Functions):
await cnk.flush();
// On graceful shutdown of a long-running process — flushes, then refuses new signals:
await cnk.close();
// How many signals are still buffered:
cnk.pending;On Vercel & serverless
Serverless functions freeze on return — buffered signals never send unless you flush first.
Flush after the response so metering never adds latency to your handler:
// Next.js App Router route handler on Vercel:
import { after } from "next/server"; // or: import { waitUntil } from "@vercel/functions";
export async function POST(req: Request) {
const out = await callLLM(/* … */);
cnk.signals.credit({
customerId: "cus_abc123",
model: "gpt-4o",
agentKey: "pro_credit",
tokens: { input, output },
});
after(() => cnk.flush()); // runs after the response is sent, before the instance freezes
return Response.json(out);
}waitUntil(cnk.flush()) from @vercel/functions works the same way. Or skip
buffering entirely — use sync mode / { wait: true } and pay the latency.
Retries & idempotency
Reads, deletes, and metering signals retry automatically. Writes like
customers.create / purchases.create don't — a blip can't create a
duplicate.
- Retried: network errors, timeouts,
408,409,429,5xx. Exponential backoff with jitter; honoursRetry-After. The signal endpoints send429when your organisation sends more than its limit of signals in one second (200 a second by default);events.clocknext.comaddsRetry-After. - Never retried:
400/401/404/422.
Idempotency — two layers:
- SDK retries (automatic). One auto-generated key per call, reused across its own retries. Covers network blips between you and Clocknext only.
- Your retries (manual). A crash or redelivery re-runs your code from
scratch — a fresh call gets a fresh key, so layer 1 doesn't help. Pass
your own
idempotencyKeyto dedupe those.
Works over raw HTTP too — it's not SDK-exclusive. No key, no protection: a retry you do yourself will double-count.
cnk.signals.credit({
customerId: "cus_abc123",
model: "gpt-4o",
agentKey: "pro_credit",
tokens: { input: 1200, output: 480 },
idempotencyKey: `chat:${requestId}`, // survives restarts; the server dedups repeats
});Every signal takes idempotencyKey — credit, wallet, outcome, outcome
complete, unit, and composite complete.
Signals
One idempotencyKey is one signal. The key belongs to your workspace and is
shared by all six signal endpoints on events.clocknext.com:
- First request with a key →
202with a newsignalIdandreplayed: false. - Any later request with the same key, within 3 days →
202with the first request'ssignalIdandreplayed: true. Nothing new is recorded or counted. This holds on any signal endpoint, for any customer and any valid body: a reused key is never a400or422. - 2 requests with the same key at the same moment → both get
202. Only one of them is counted. - After 3 days the key is forgotten: reusing it records a new signal.
- Keys are trimmed. Case is kept:
Order-1andorder-1are two keys.
So use a new key for every new signal, and keep the same key only when you send the same signal again.
{
"statusCode": 202,
"statusDetail": { "status": "SUCCESS", "message": "Signal accepted for processing." },
"result": { "queued": true, "signalId": "0192ab3c-7f10-7a51-9c2e-3b4d5e6f7a80", "replayed": true }
}These rules differ from the balance adjustments below, where a key belongs to
one adjust endpoint and a different request with the same key is a 422.
Balance adjustments
The adjust endpoints (/customers/{id}/credits|outcomes|units|composites|wallet/adjust)
take the same two layers as signals. The SDK keys every adjustment for you
(one auto-generated key per call, reused across its retries), so a network blip
never adjusts twice. Over raw HTTP there is no automatic key — send one yourself.
Pass your own idempotencyKey (1–255 characters; your order or top-up id works
well) to also make your own retries safe:
- Same key, same request → nothing is adjusted again.
200withreplayed: true,adjustedAt(when the original happened) and the currentremaining. The message starts "Already processed". - Same key, different request (another customer, entitlement or amount) →
422, nothing adjusted. Use a new key for a new adjustment. - A failed adjustment never uses up its key — fix the request and resend it with the same key.
- Keys are unique per workspace and per adjust endpoint.
curl -X POST https://payments.clocknext.com/api/v1/customers/cus_abc123/credits/adjust \
-H "Authorization: Bearer $CLOCKNEXT_API_KEY" \
-H "Content-Type: application/json" \
-d '{ "agentKey": "pro_credit", "delta": 500, "idempotencyKey": "topup:ord_1042" }'const res = await cnk.customers.adjustCredit("cus_abc123", {
agentKey: "pro_credit",
delta: 500,
idempotencyKey: `topup:${orderId}`, // optional — the SDK generates one if you omit it
});
if (res.replayed) {
// Already applied at res.adjustedAt — nothing was added this time.
}Credit notes, plan changes and invoice-balance adjustments
POST /credit-notes, POST /plan-changes and POST /customers/{id}/invoice-balance/adjust
(and its ext/{externalId} twin) take an optional idempotencyKey (1–200
characters; 1–255 for the balance adjustment). The SDK makes one for you
(one per call, reused across its retries); over raw HTTP, send your own.
- Same key, same request → nothing new is made.
200withreplayed: true. - Same key, different request →
422withstatusDetail.codeIDEMPOTENCY_KEY_REUSED. Use a new key for a new request. For a plan change,startNewCycleis part of the request: the same key with the other answer is refused this way too, but only for a plan on the same billing cycle whose change invoiced something.
Refunds
POST /refunds requires an idempotencyKey, and the SDK never makes one for
you: it is what stops a retry from refunding the customer twice. Send the
same key to retry the same refund, and a new one for a new refund. A
repeat comes back 200 with replayed: true and the payment gateway is not
asked again. The same key with another amount is a 422
IDEMPOTENCY_KEY_REUSED.
const { refunds, replayed } = await cnk.refunds.create({
customerId: "cus_abc123",
amountUsd: 40,
idempotencyKey: `refund:${ticketId}`, // required — reuse it only to retry this refund
});Cancelling with a refund
POST /subscriptions/{id}/cancel takes no idempotencyKey. A cancel that refunds
the unused time (proration: "REFUND_UNUSED_TIME") is made once per
subscription, so a retry can't refund the customer twice. If the cancel failed
after the refund was made, ask again with the same refundTo: the refund is not
repeated and only the cancel is finished. A retry with another refundTo is a
409 REFUND_DESTINATION_MISMATCH, and a retry whose refund note was voided is a
409 CANCEL_REFUND_VOIDED; neither cancels anything.
The answer always carries creditNoteId when a refund was made. The cancel is
already done when the answer is built, so an object that could not be loaded
(subscription, creditNote or invoice) is null, and creditNoteId tells
you the refund was made.
While a plan change of the subscription is being made, every cancel of it is
refused with a 409 PLAN_CHANGE_IN_PROGRESS, so the same unused time is not
credited twice. Nothing is changed, so it is safe to ask again in a few minutes.
Durability: the buffer is in-memory
A signal the server has already accepted is durable on the server. But signals still sitting in the async buffer when a process crashes (before send) are lost — there is no on-disk spool. For zero-loss-before-receipt:
- run in
syncmode (or pass{ wait: true }) so the send completes before your code continues, or await cnk.flush()/cnk.close()at your function/shutdown boundaries.
When the buffer is full (batch.maxQueueSize, default 10 000) new signals
are dropped rather than queued without bound — observe both drops and permanent
failures with the hooks:
new ClockNext({
apiKey: process.env.CLOCKNEXT_API_KEY!,
onError: (err, signal) => report(err, signal), // permanent failure (after retries / non-retryable)
onDrop: (signal, reason) => report(reason), // "queue_full" | "send_failed"
onFlush: (count) => metrics.add("flushed", count),
});Configuration
Every knob is optional; a bad value (negative / non-finite) falls back to its default rather than breaking the client.
Prop
Type