Skip to main content

Audit logging for a multi-tenant e-commerce platform

A multi-tenant commerce platform has many merchants, each with staff, orders, products and payouts. Every sensitive action — a refund, a price change, a payout — needs to land in an audit log under the merchant it belongs to. This guide maps the platform onto Santati: one organization per merchant, a server-side helper that emits events, and a read endpoint each merchant's staff can use.

The outcome: every sensitive action is recorded under the merchant it belongs to, each merchant can read its own log, and retention is set per merchant. An organization is the anchor for retention, residency and legal hold, so one organization per merchant is what makes per-merchant retention possible at all.

Before you start: a Santati account, a trail named commerce and a write key in SANTATI_API_KEY (Quickstart), Node 22+, and npm install @santati/node.

Map your platform onto Santati​

Your platformSantati
The platform itselfYour team
A merchantAn organization whose organization_id is your merchant id
A merchant's staff memberAn actor of type user
A background job or payment webhookAn actor of type system
An order, product, payout or discountA target
The product areaThe trail commerce

The first event naming a new organization_id creates the organization, named after the id, with a 12-month retention window capped by the plan. That automatic creation is a per-team setting, on by default. Organizations cannot be created over the API, and they are permanent. A self-serve platform leaves automatic creation on and derives the id on the server, from the merchant the staff member belongs to. An id is matched exactly, after trimming whitespace and clipping to 255 characters.

Decide what to record​

AreaRecordAction names
Orders and moneyRefunds, cancellations, discounts, payouts and payout-account changesorder.refunded, order.canceled, discount.created, payout.sent, payout_account.updated
CatalogPrice and stock changes made by staff or importsproduct.price_changed, product.deleted, inventory.adjusted
Customer dataExports and bulk downloads of shopper datacustomer_data.exported
Staff and accessInvitations, role changes, removals, sign-insinvitation.sent, member.role_changed, member.removed, user.signed_in, user.sign_in_failed
Keys and integrationsAPI keys, webhooks and apps a merchant connectsapi_key.created, api_key.revoked, webhook.created, integration.connected
SettingsTax, shipping and checkout settingssettings.updated

Action names are <resource>.<past_tense_verb> in snake_case. The names in the rows "Staff and access", "Keys and integrations" and "Settings" are standard events your team installs; the other rows are names of your own.

warning

Installing a standard pack, or defining any action, turns enforcement on for the team, and an action outside the catalog is then refused with unknown_action. Define the commerce actions first; see Event definitions.

Shopper browsing and carts are analytics, not audit; leave them out. source, reason and request_id are optional on every standard action; old and new values, and PII such as email addresses, go in data, not metadata.

Emit from one server-side helper​

audit.ts
import { Santati, type EventInput } from "@santati/node";

export const santati = new Santati({
apiKey: process.env.SANTATI_API_KEY!,
trail: "commerce",
});

// Built by your auth middleware from the signed-in session, never from request parameters.
export type Session = {
merchantId: string;
userId: string;
userName: string;
ip?: string;
userAgent?: string;
requestId?: string;
};

type AuditInput = Pick<EventInput, "event" | "targets" | "metadata" | "data">;

export async function audit(session: Session, input: AuditInput): Promise<void> {
try {
await santati.events.emit({
...input,
organizationId: session.merchantId,
actor: { type: "user", id: session.userId, name: session.userName },
context: {
location: session.ip,
user_agent: session.userAgent,
request_id: session.requestId,
},
});
} catch (error) {
// The action already happened: losing its audit record must be loud, not fatal.
console.error("audit event not recorded", input.event, error);
}
}

organizationId comes from the session, never from request parameters, because it decides whose log the event lands in. metadata is a flat map of strings for the few values you filter on: at most 50 keys, values at most 500 characters. Before and after values and personal data go in data, which is stored verbatim. context carries transport facts. A failed emit is logged, not raised, because the action has already happened.

A refund:

await audit(session, {
event: "order.refunded",
targets: [{ type: "order", id: order.id, name: order.number }],
metadata: { source: "ui", reason: "damaged_item" },
data: { refund_id: refund.id, amount_cents: refund.amountCents, currency: order.currency },
});

A background job, in audit.ts beside the helper:

await santati.events.emit({
event: "payout.sent",
organizationId: merchant.id,
actor: { type: "system", id: "payout-scheduler" },
targets: [{ type: "payout", id: payout.id }],
data: { amount_cents: payout.amountCents, currency: payout.currency },
});

Make delivery survive a crash​

The SDK retries transport failures, 500, 502, 503, 504 and 429 (except quota_exceeded) up to twice and re-sends the same idempotency key, so a retry never stores an event twice. That covers a network blip, not a process that dies between the database commit and the emit. For actions that must not be lost, write the event to an outbox table in the same transaction and drain it:

// `outbox` is your own table: one { id, event } row written in the same transaction as the change.
const rows = await outbox.takePending(500);

const batch = await santati.events.emitBatch(
rows.map((row) => ({ ...row.event, idempotencyKey: row.id })),
);

for (const item of batch.results) {
const row = rows[item.index];
if (item.status === "rejected") {
await outbox.markFailed(row.id, item.error);
} else {
await outbox.markSent(row.id, item.id);
}
}

A batch holds at most 500 events and 1 MiB. Each item reports accepted, duplicate or rejected. A key replays for 24 hours, so a row drained twice comes back duplicate. After the window the key is spent and a retry writes a new event, so drain the outbox well inside it. A batch counts as one request and N events against the per-minute ceilings; see Rate limits, Batching and Idempotency.

Show each merchant its own log​

const reader = new Santati({ apiKey: process.env.SANTATI_READ_API_KEY! });

// Behind your own route, for example GET /admin/audit-log?cursor=…
export async function merchantAuditLog(session: Session, cursor?: string) {
const page = await reader.events.list({
organizationId: session.merchantId,
limit: 50,
cursor,
});
return { events: page.results, nextCursor: page.nextCursor };
}

Use a separate read key. The key stays on the server and the merchant id comes from the session, so a merchant can never read another merchant's events. Events come back newest first by producer timestamp. nextCursor is null on the last page; limit defaults to 100 and is capped at 1000, and the cursor is sent back verbatim.

One order's history: reader.events.list({ organizationId: session.merchantId, targetType: "order", targetId: orderId }). One staff member: actorId. For a full download start an export with organization_id in its query (Export events).

Set retention and holds per merchant​

Audit Log → Organizations lists every merchant. A team administrator extends a merchant's retention there and places or releases a legal hold. Retention can only be extended and is capped by the plan. On a paid plan, stored events above the plan's included amount are billed, so each merchant's window also sets what its events cost. A hold suspends deletion until it is released, and holds are never deleted: the history keeps who placed and who released each one. See Organizations and Retention and legal holds.

Next steps​

A log stream whose match rule lists one merchant in organization_ids delivers that merchant's events to an HTTPS endpoint (Log streams). Verify a trail's chain with Chain verification. When agents act for merchants, see Deployed AI agents.