Skip to Content
API ReferenceEvent Log

Event Log

Every change Foir makes to your project is written to a durable event log, in the same database transaction as the change itself. The log is the answer to “what happened, in what order, and who did it” — and, because each entry carries the resource’s state as of that moment, it is enough to rebuild a downstream copy of your data without calling back for anything.

You read it forward from a cursor. A pipeline stores the position it reached, comes back an hour or a day later, and resumes exactly there.

Back-office surface. The event log is readable with an admin key or a console session. It is not readable with a publishable or a server key and not readable with a user token — there is no browser-side or user-facing form of this API. See Who can read it for why, before you design around it.

Who can read it

Reading the log requires the events:read scope, and that scope can only be granted to an admin key. Granting it to a publishable or a server key is rejected when the key is created, and a user token can never carry it, whatever key accompanies the request.

That is narrower than it looks at first glance, and it is deliberate. A record read is filtered by ownership: a user sees their own rows, rows shared with them, and rows the project has made public. The event log is filtered only by project — so an unfiltered read of it describes changes to records the same caller could not open. Each entry also names the actor behind the change. Opening this to users would hand one user a per-record activity feed of another user’s actions, in exactly the projects where ownership rules exist to prevent that.

So: read the log from a server, a worker, or a scheduled job, with a key that never reaches a browser. If you need to show activity to a user, derive it from a read you have already narrowed to that user, not from this API.

Widening this later would be easy. Narrowing it after people had built on it would not, which is why it starts here.

What an event is

One entry looks like this:

{ "id": "hbwawuxu8sgfbc77yu1a2lh2", "seq": 4182, "event": "RECORD_PUBLISHED", "payload": { "recordId": "rec_9f2c", "modelKey": "page", "tenantId": "tnt_3a91", "projectId": "prj_6b02", "state": null, "stateSchema": 1 }, "actor": { "kind": "user", "ref": "user:usr_7c31" }, "causationChain": ["op_2f81"], "createdAt": "2026-08-07T10:14:02.881Z" }
FieldWhat it is
idThe event’s own identifier. Stable, and the right key to de-duplicate on if you ever replay a range.
seqThis event’s position in the project’s stream. The cursor — see The seq cursor.
eventThe registry name, e.g. RECORD_PUBLISHED. The readable set is listed under Filtering by event.
payloadThe event’s own keys, plus state and stateSchema. state is self-contained — the resource’s state as of the event, not a pointer to current state — for user, session and operation events. It is null for RECORD_* events, whose payload is the {recordId, modelKey, tenantId, projectId} pointer you read back under your own credentials. stateSchema versions the snapshot’s shape.
actorWho caused it, as kind and ref. A person is kind user with ref user:<id>, whichever pool they sign in to; a key, a service or Foir’s assistant has its own kind. null when the change was attributed to nobody, which is preserved rather than flattened into an empty object, so an unattributed event is visible as one.
causationChainThe operation keys that led here, oldest first. Empty when the change was not caused by an operation.
createdAtWhen the change committed. RFC 3339.

A record event carries no version pointer. The payload names the record and where it lives; it does not say which version the change produced, and there is no versionId key on it. To find out, resolve the record and read its currentVersionId, which means the answer you get is the version as of your read, not as of the event. If you need the exact version a RECORD_PUBLISHED produced, capture it at the moment you receive the event rather than later.

Where a snapshot is carried, it is what makes the log worth reading rather than polling: a late consumer, a replay, and a backfill all see what was true at the time, not what is true now. RECORD_* events are the exception — they carry the pointer only, so reading one back resolves the record as it is now, and a record deleted since resolves nothing.

Reading the log

The typed client lives on @foir/sdk/server — the SDK’s server-only entry point, which has no React dependency and runs in Node or a Cloudflare Worker.

import { createEventsClient } from '@foir/sdk/server'; const events = createEventsClient({ apiUrl: process.env.PLATFORM_API_URL!, apiKey: process.env.FOIR_ADMIN_KEY!, // foir_adm_… holding events:read }); const page = await events.list({ after: 0, limit: 500 }); for (const event of page.events) { console.log(event.seq, event.event, event.actor?.ref ?? 'unattributed'); } console.log(page.nextCursor, page.hasMore);

createEventsClient throws if you hand it a publishable or a server key, and it does not accept an Authorization header — a user bearer token would make the user the caller, and no user can read this. Both refusals happen when you build the client, not when the request comes back.

For a consumer that just wants everything since it last ran, stream() pages forward for you and yields events one at a time. It finishes when it reaches the end of the log; it does not poll, so the interval is yours to choose.

let cursor = await loadCursor(); // whatever you persisted last time for await (const event of events.stream({ after: cursor })) { await handle(event); cursor = event.seq; await saveCursor(cursor); }

Saving the cursor after handling each event is the shape to copy. If the process dies mid-page, the next run re-reads from the last event it finished, so an event is processed at least once and never zero times. Make handle idempotent — de-duplicate on event.id — and that is the whole delivery contract.

Subscribing instead of polling

stream() drains the log and stops, which is what a cron job or a one-shot backfill wants. A process that stays open can have the same events pushed to it instead:

const subscription = events.subscribe({ after: await loadCursor(), // omit to start at the live edge onData: async (event) => { await handle(event); await saveCursor(event.seq); }, onError: (err) => reportAndRestart(err), }); // later subscription.unsubscribe();

This is the same cursor, not a second delivery system. The server backfills from after and then continues live on one stream, so there is no window between catching up and keeping up where an event could fall through, and no second code path to write for the two phases.

The cursor advances as events arrive. If the socket drops, the SDK reconnects and resubscribes from the last event it delivered to you — not from the after you originally passed — so a reconnect does not replay everything you have already handled.

onData is still at-least-once. A socket that drops after the server sent an event but before you finished handling it will re-deliver that event on reconnect, exactly as the paging lane re-reads a partly-processed page. The same rule applies: de-duplicate on event.id.

The socket needs a WebSocket constructor. Browsers, Deno, Bun, Cloudflare Workers and Node 22+ have a global one and need nothing; on Node 18 or 20, pass the ws package’s:

import { WebSocket } from 'ws'; const events = createEventsClient({ apiUrl: process.env.PLATFORM_API_URL!, apiKey: process.env.FOIR_ADMIN_KEY!, webSocketImpl: (url, protocols) => new WebSocket(url, protocols), });

The authority rule is the one from Who can read it, unchanged: the socket authenticates with the same admin key, and a user bearer token on it makes the user the caller, whose authority never contains events:read.

A cursor older than the retention window ends the subscription rather than skipping ahead — see When a cursor expires, which behaves identically on both lanes.

The seq cursor

seq is a 64-bit integer, monotonically increasing within one project, assigned in commit order.

Commit order, not insert order, is the part that matters. Two transactions can begin in one order and commit in the other; a cursor built on timestamps or on insert order would let a reader step past an event that was still uncommitted when its page was served, and never see it again. seq is assigned once the write has landed, and a reader only ever sees events that have been assigned one — so resuming from a stored seq cannot skip an event.

Three things to know about it:

  • It is per project. Two projects have unrelated sequences. Comparing a seq from one against a seq from another means nothing.
  • Gaps are normal, and are not lost events. A filtered read returns only matching events, so the numbers you see will jump. seq is for comparing, not for counting: nothing is missing because 4182 followed 4179.
  • nextCursor never moves backwards. On an empty page it equals the after you sent, so persisting it unconditionally is always safe.

Store it as a number, not as an opaque token. It is yours to reason about — a monitor can alert on how far behind the stream a consumer has fallen, which is not something an opaque cursor could tell you.

Ordering

Within the read API, ordering is settled: a page is returned in seq order, ascending, and paging forward visits every event exactly once.

Webhook deliveries are a different matter — they are dispatched concurrently and a retry can land behind a delivery sent after it, so a receiver that writes bodies through to its own database can overwrite newer data with older. That is a receiver obligation, not something the read API changes; it is written up on Webhooks. If you need ordering guarantees, read the log rather than relying on the order deliveries arrive in.

Filtering by event

Pass one or more event names to narrow the stream. The names are the registry’s, and they are the same ones you subscribe a hook to — Hook Events is the generated catalogue, with the payload keys each one carries.

const publishes = await events.list({ after: cursor, events: ['RECORD_PUBLISHED', 'RECORD_UNPUBLISHED'], });

The log is a project stream, so the events it serves are the project-plane ones:

FamilyEvents
RecordsRECORD_CREATED, RECORD_UPDATED, RECORD_DELETED, RECORD_PUBLISHED, RECORD_UNPUBLISHED
UsersUSER_CREATED, USER_UPDATED, USER_DELETED, USER_MERGED, USER_PREFERENCE_CHANGED
SessionsSESSION_REVOKED
OperationsOPERATION_COMPLETED, OPERATION_FAILED, OPERATION_CANCELLED, OPERATION_TIMED_OUT
Imports and migrationsIMPORT_COMPLETED, MIGRATION_APPLIED
Bulk writesBULK_UPDATE_COMPLETED, BULK_PUBLISH_COMPLETED
OrganizationsORGANIZATION_CREATED, ORGANIZATION_UPDATED, ORGANIZATION_MOVED, ORGANIZATION_SUSPENDED, ORGANIZATION_RESUMED, ORGANIZATION_DELETION_SCHEDULED, ORGANIZATION_DELETION_CANCELLED, ORGANIZATION_DELETED, ORGANIZATION_MEMBER_ADDED, ORGANIZATION_MEMBER_REMOVED, ORGANIZATION_MEMBER_ROLE_CHANGED
Join requestsJOIN_REQUESTED, JOIN_REQUEST_APPROVED, JOIN_REQUEST_DECLINED

Workspace-plane events (memberships, plan and subscription changes, project creation, archival and reactivation, invitations) belong to the workspace rather than to any one project, so they are not served here. Subscribe a workspace hook for those.

Names are exact and case-sensitive: it is RECORD_CREATED, not record.created.

Retention: 90 days

The log serves a flat 90-day window. There is no longer window on a larger plan — a retention period that varied by plan would make the answer to “how far back can I resume from” plan-dependent, which is a worse trade than the storage it would save.

The window is enforced on every read, so it does not depend on when storage was last reclaimed: an event older than 90 days is outside the contract whether or not its rows are still on disk.

Every page reports the window, whether or not anything is wrong:

const page = await events.list({ after: cursor }); console.log(page.retention.windowDays); // 90 console.log(page.retention.oldestRetainedAt); // the oldest createdAt served console.log(page.retention.oldestAvailableSeq); // the lowest seq still inside it

oldestAvailableSeq is the one to watch. A consumer that compares its stored cursor against it on every page can alert while it still has runway, instead of discovering the problem as a failure. A cursor approaching that number is a consumer falling behind.

When a cursor expires

If your cursor points behind the oldest event still inside the window, events you had not read have expired. The API refuses rather than serving a shortened page.

That is deliberate. Returning a partial page with a flag set would make silent data loss the default for every consumer that did not read the flag. A refusal cannot be ignored, and it names the position to resume from — so acknowledging a gap is one line of code you wrote on purpose.

import { createEventsClient, FoirEventCursorExpiredError } from '@foir/sdk/server'; try { page = await events.list({ after: cursor }); } catch (err) { if (err instanceof FoirEventCursorExpiredError) { // err.resumeFrom is the cursor to continue from, accepting the gap. await alertOnCall(`event log gap: ${cursor} to ${err.resumeFrom}`); page = await events.list({ after: err.resumeFrom ?? 0 }); } else { throw err; } }

On the wire this is 410 Gone over REST, and a failed_precondition carrying the marker cursor_expired over GraphQL. It is deliberately not a 404: the stream exists, you are allowed to read it, and the events you asked for existed and were removed on a published schedule. 410 says exactly that, and it is the difference between debugging a cursor and debugging an endpoint.

subscribe() reports the same condition the same way, through onError rather than a throw, and the subscription ends there — a stream that silently resumed at the live edge would be the shortened page this whole surface refuses to serve:

events.subscribe({ after: cursor, onData: handle, onError: async (err) => { if (err instanceof FoirEventCursorExpiredError) { await alertOnCall(`event log gap: ${cursor} to ${err.resumeFrom}`); resubscribeFrom(err.resumeFrom ?? 0); // accepting the gap, on purpose } }, });

Errors

StatusCodeMeaning
400INVALID_ARGUMENTafter or limit was not a non-negative integer, or an event filter was sent with no names in it.
401UNAUTHENTICATEDNo API key, or the key is not valid.
403PERMISSION_DENIEDThe caller is not permitted to read the log — the key lacks events:read, or a user token is present and is therefore the caller.
410FAILED_PRECONDITIONThe cursor is older than the retention window. See When a cursor expires.
429RATE_LIMITEDThe key has spent its allowance for the window. Retryable; honour Retry-After.

Errors from the events client are FoirRequestErrors, the same class the rest of the SDK throws, so the existing helpers work on them:

import { isFoirForbidden, isFoirRateLimited } from '@foir/sdk/server'; try { await events.list(); } catch (err) { if (isFoirRateLimited(err)) await sleep(err.retryAfterMs ?? 60_000); else if (isFoirForbidden(err)) throw new Error('key is missing events:read'); else throw err; }

The REST endpoint

The same read, for a consumer that is not a JavaScript client — a shell script, a Lambda, an ETL step.

GET https://api.foir.dev/v1/events
ParameterMeaning
afterExclusive cursor: return events with seq greater than this. Omit or send 0 to start at the oldest event in the window.
limitPage size. Defaults to 100, capped at 1000.
eventFilter by event name. Repeat the parameter for several names — event=RECORD_CREATED&event=RECORD_UPDATED — rather than comma-joining them.
curl -sS "https://api.foir.dev/v1/events?after=4181&limit=100&event=RECORD_PUBLISHED" \ -H "x-api-key: foir_adm_..."

The body is the same page in snake_case:

{ "events": [ { "id": "hbwawuxu8sgfbc77yu1a2lh2", "seq": 4182, "event": "RECORD_PUBLISHED", "payload": { "recordId": "rec_9f2c", "modelKey": "page", "tenantId": "tnt_3a91", "projectId": "prj_6b02" }, "actor": { "kind": "user", "ref": "user:usr_7c31" }, "causation_chain": [], "created_at": "2026-08-07T10:14:02.881Z" } ], "next_cursor": 4182, "has_more": false, "retention": { "window_days": 90, "oldest_retained_at": "2026-05-09T00:00:00Z", "oldest_available_seq": 1 } }

The SDK client camelCases these for you and normalises the two nullable fields, so actor stays null and causationChain is always an array.

Note that this endpoint is not response-cached, unlike the GraphQL API. That is on purpose: a cached page of a log can hand a consumer events it has already processed while claiming there is nothing left.

The GraphQL field

The log is also a root field, for callers already speaking GraphQL. It takes first where the REST endpoint takes limit, and returns camelCase throughout.

query ProjectEvents($after: EventSeq, $first: Int) { events(after: $after, first: $first, events: ["RECORD_PUBLISHED"]) { events { id seq event payload actor causationChain createdAt } nextCursor hasMore retention { windowDays oldestRetainedAt oldestAvailableSeq } } }

The SDK counterpart is the same client as everywhere else on this page:

import { createEventsClient } from '@foir/sdk/server'; const events = createEventsClient({ apiUrl, apiKey }); const page = await events.list({ after, limit: first, events: ['RECORD_PUBLISHED'] });

seq is a custom EventSeq scalar rather than Int, because GraphQL’s Int is 32-bit and a busy project’s stream would start returning nulls for the one field a consumer’s correctness depends on. It serialises as a JSON number and accepts a number or a decimal string on input.

Prefer the SDK or the REST endpoint for log consumption. GraphQL responses go through the response cache, which is the wrong behaviour for a cursor-paged log.

See also

  • Hook Events — the generated catalogue: every event name, what produces it, and the payload keys it carries.
  • Authentication — granting events:read to an admin key.
  • Webhooks — push delivery of the same events, and the ordering obligations that come with it.
  • Errors & Rate Limits — the shared error codes and retry guidance.
Last updated on