Send events from your own servers
Server events let your own backend send events, such as an account created, a payment confirmed or a nightly job finished, into the analytics of one of your websites: a title's Game website or your company website. Your server sends them over HTTPS with the website's secret server key, and they have their own Server events report, kept apart from what visitors do in the browser.
When to use server events
Send each event from the place that knows first that it happened.
| What happened | Send it with |
|---|---|
| A visitor opened a page or clicked on your website | The website snippet in the browser, with the website's public key |
| Your server did something: created an account, confirmed a payment, received a webhook, finished a scheduled job | Server events, with the website's secret server key |
| A player did something in your game | The SDK for your engine or the HTTP API, with the game's ingest key |
Server events belong to a website, not to a game. They need no game, environment or session, and they never appear in a game's reports. When the event is about a player in your game, such as a purchase your game server confirms, send it to the game instead: your game server can join the player's session and track the event there.
Server events show only in their own report. They never change any other website report, so visitors, page views, events, goals and funnels stay what the browser saw (see where the events show).
Create the server key
Each website has at most one server key. Owners, admins and members, the roles that can configure a website, can create, replace and revoke it.
- Open the website's setup. For your company, open website setup from the Company website card on Company home. For a title, select its project and open Live data > Game Website, then Setup. Collect website activity must be on: while it is off, the key is refused.
- In the Server key card, choose Create server key. The key starts with
gt_srv_. - Copy it straight into your server's secret settings, for example an environment variable named
RAVENSIGHT_SERVER_KEY. The key is shown this once. Ravensight stores only a one-way hash of it and cannot show it again.
Afterwards the card shows the key's first characters, when it was created and when your backend last used it. Replace key makes a new key, shown once, and the old key stops working at that moment, so update your server straight away. Revoke removes the key, and requests that carry it are refused from then on. Removing the website removes its key.
Server events do not mark the website as installed. Verify installation still waits for the browser snippet; the key's last use is what shows your backend is sending.
Keep the key on your server. Anyone who holds it can
add events to your website, and those events count toward your
studio's usage. Never put it in a web page, a game build, a mobile app
or a repository; the website snippet's public key is the one made for
browsers. A request that carries an Origin header, as
every browser request does, is refused with
403 server_only, so a server key never works from a web
page. No MCP tool or agent token can read or change it.
Send a request
Request
POST https://api.ravensight.io/api/v1/site/server-events
Authorization: Bearer gt_srv_...
Content-Type: application/json
{
"events": [
{
"eventId": "7c9e6679-7425-40de-944b-e07fc1f90ae7",
"name": "account_created",
"timestamp": 1795076742620,
"actorId": "account-48213",
"properties": { "plan": "free", "method": "password" }
}
]
}
One request carries 1 to 50 events. The JSON body may be at most
512 KB, counted after any gzip is undone, and you may send it
compressed with Content-Encoding: gzip. Send no cookie and
no Origin header. The body holds only
events, and each event only the five fields below. It never
names a website, studio or game: the key alone decides which website
the events join and which studio's usage they count toward.
| Field | Rules |
|---|---|
eventId | Required. 8 to 128 letters, digits, _, ., : or -. Make a new one when the event happens, such as a random UUID, and keep it for every retry (see retries and duplicates). |
name | Required. A letter, then up to 79 letters, digits, _, . or -, such as account_created. |
timestamp | Required. When it happened, as a whole number of Unix milliseconds. At most 5 minutes ahead and 90 days back. |
actorId | Optional. Your own opaque id for the person or device the event is about, 8 to 128 letters, digits, _, ., : or -. Never an email address. Leave it out for an event about your backend itself. |
properties | Optional. Up to 24 flat keys and values (see actors and properties). |
The whole batch is checked before anything is stored or charged. One
event that breaks a rule refuses the request with a 400,
and nothing in it is recorded.
Limits. 600 requests a minute for each key, and 6,000
events a minute for one website. Past either, the answer is
429 rate_limited with a Retry-After header.
Actors and properties
actorId says who or what the event is about: the id your
own database already uses for an account, a player or a device. It
must be opaque. An email address, a name or a phone number is never an
actor id, and the allowed characters leave no room for an email
address. A short number needs a prefix to reach 8 characters, such as
account-42.
Ravensight never stores the id you send. It stores a keyed one-way
hash of it, made separately for each website, so the same id sent to
two websites counts as two different actors, and your id cannot be
read back. The report counts how many different actors sent each
event. Events sent without an actorId belong to your
backend itself and are never counted as an actor.
Properties follow these rules:
- At most 24 keys. A key is a letter, then up to 63 letters, digits or underscores.
- Some keys are reserved, in any letter case: keys that start with
rs_,history_orravensight_, and the keyscontext,identity_kind,session_provenanceandprofile_provenance. - A value is a string of at most 200 characters, a finite number,
true,falseornull. No lists and no nested objects. - All of an event's properties together are at most 4 KB as JSON.
- A string that looks like a person or a credential is refused: one that holds an
@, a label such aspassword=,token:orBearerfollowed by a space, a signed web token, a Ravensight key, or 80 or more letters and digits in a row.
A property that breaks a rule is answered with
400 invalid_properties. Keep identifiers in
actorId, never in properties.
Answers and errors
Response, 200
{
"accepted": 2,
"duplicates": 1,
"conflicts": 0,
"refused": 0,
"acceptedIds": ["7c9e6679-7425-40de-944b-e07fc1f90ae7", "...", "..."],
"conflictIds": [],
"refusedIds": [],
"paused": false
}
Every event in the request is counted once:
accepted: stored now.duplicates: already stored with the sameeventIdand content, so not stored or charged again.acceptedIdslists both of these.conflicts: aneventIdalready stored with different content. Only those events are refused, listed inconflictIds; the rest of the batch is stored.refused: stopped by a pause, listed inrefusedIds. Collection pauses when your studio's included events are used up and the prepaid balance cannot cover more. The answer then has"paused": trueand areason:needs_funds, orbackstopat the monthly safety ceiling, where adding funds does not help. After adding funds, send the refused events again with the same ids.
When a pause means nothing in the request was accepted, the status is
429 with "error": "collection_paused" and the
same fields. Any other error answer names its code in
error.
| Answer | Meaning, and what to do |
|---|---|
400 invalid_events | The body is not JSON, holds a field it should not, or is not a list of 1 to 50 events; or an event has a field missing, of the wrong type or outside its rules. Nothing was stored. Fix the request: sent again unchanged, it fails the same way. |
400 invalid_timestamp | A timestamp is more than 5 minutes ahead or more than 90 days back. Nothing was stored. Check your server's clock, and drop events older than 90 days. |
400 before_cutover | A timestamp is earlier than this website's cutover, the point set when its earlier history was imported. Nothing was stored. Send only events from after the cutover. |
400 invalid_properties | A property breaks the rules above. Nothing was stored. Fix or remove the property. |
401 missing_server_key | No Authorization header. Send the key. |
401 invalid_server_key | The key is unknown, was replaced or revoked, or its website is removed or has Collect website activity off. Use the website's current key, and check that collection is on. |
403 server_only | The request carried an Origin header, as every browser request does. Send from your server only. |
404 not_found | Website analytics is not available. Nothing was stored. |
409 site_changed | The website, its settings or its key changed while the request was handled, or too many of its events are waiting to be stored. Send the same request again shortly with the current key: events already accepted come back as duplicates. |
413 payload_too_large | The body is over 512 KB after gzip is undone. Send fewer events in each request. |
429 rate_limited | Over 600 requests a minute with one key, 6,000 events a minute for one website, or 3,000 requests a minute from one sending address, which backends on a shared address count together. Wait the seconds in Retry-After, then send the same request again. |
429 collection_paused | Nothing was accepted: the included events are used up and the balance cannot cover more (needs_funds: add funds, then send the refused events again), or the account reached the monthly safety ceiling (backstop). |
5xx, a timeout or no answer | The request may or may not have been stored. Send the same request again, waiting longer each time. |
Retries and duplicates
eventId makes a request safe to send again. Ravensight
stores an event once for each website and id: the same id with the same
content is answered as a duplicate, stored once and charged once. The
same id with different content is counted in conflicts
and not stored. So give each event its own id when it happens, keep the
id and everything else about the event for every retry, and set the
timestamp when the event happens, never when you send it.
Retry when there was no answer (a network error or a timeout), a
5xx, a 429 rate_limited or a
409 site_changed: wait, send the same events again, and
wait longer each time. Never retry any other 4xx
unchanged, because it fails the same way again. After a timeout,
resend the whole batch: the events that did get stored come back as
duplicates, and they are free. Events refused by a pause can wait and
be sent again once you add funds.
An id from your own records works too, as long as it names one event,
such as payment-8812-confirmed. That lets an event that
must never be lost, such as a payment, be written to your own database
with the payment and sent from there until it is accepted.
Example for Node
A complete sender for Node 18 or newer in one file. It has no
dependencies and uses only the built-in https module.
- It keeps a queue in memory of at most 10,000 events. Past that it drops the oldest, so an outage cannot fill your server's memory.
- It sends batches of up to 50: as soon as 50 are waiting, and every 5 seconds otherwise.
- Each request gets 10 seconds. No answer, a
5xx, a429or a409 site_changedis retried up to five times, waiting about 1, 2, 4, 8 and 16 seconds or theRetry-Afterthe answer gives, then the batch waits in the queue for the next flush. Any other4xxis logged and never retried. - Every retry sends the same body, so the same
eventIdvalues. - When collection pauses, it keeps the refused events and sends them on a later flush. It logs any conflicts.
- It reads the key from the
RAVENSIGHT_SERVER_KEYenvironment variable, and checks names, actor ids and properties against the rules above when you calltrack, so a mistake throws in your code instead of failing a whole batch later. close()sends what is left when your process shuts down.
server-events.mjs
// server-events.mjs: send Ravensight server events from Node 18 or newer.
// No dependencies. The server key stays on your server, in an environment variable.
import https from 'node:https';
import { randomUUID } from 'node:crypto';
const NAME = /^[a-zA-Z][a-zA-Z0-9_.-]{0,79}$/;
const ACTOR = /^[A-Za-z0-9_.:-]{8,128}$/;
const KEY = /^[A-Za-z][A-Za-z0-9_]{0,63}$/;
// Property keys the server keeps for itself, in any letter case.
const RESERVED_PREFIX = /^(?:rs_|history_|ravensight_)/i;
const RESERVED_KEYS = ['context', 'identity_kind', 'session_provenance', 'profile_provenance'];
const reserved = key => RESERVED_PREFIX.test(key) || RESERVED_KEYS.includes(key.toLowerCase());
// String values the server refuses because they look like a person or a credential.
const CREDENTIAL = /@|%40|(?:bearer|password|secret|token|authorization)[=:]|(?:^|\s)bearer\s/i;
const TOKEN = /^eyJ[\w-]+\.|\bgt_[a-z]+_[\w-]{8,}|[\w-]{80,}/;
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
export class ServerEvents {
constructor({
key = process.env.RAVENSIGHT_SERVER_KEY,
url = 'https://api.ravensight.io/api/v1/site/server-events',
maxQueue = 10000, // past this, the oldest events are dropped
batchSize = 50, // the most one request may carry
flushMs = 5000, // send what is queued this often
timeoutMs = 10000, // give up on one request after this long
retries = 5, // tries after the first, then the batch waits for the next flush
backoffMs = 1000, // the first wait between tries; it doubles, up to 30 seconds
log = console.warn,
} = {}) {
if (!key?.startsWith('gt_srv_')) {
throw new Error('Set RAVENSIGHT_SERVER_KEY to the website server key');
}
Object.assign(this, { key, maxQueue, timeoutMs, retries, backoffMs, log });
this.url = new URL(url);
this.batchSize = Math.min(batchSize, 50);
this.queue = [];
this.flushing = null;
this.timer = setInterval(() => this.flush(), flushMs);
this.timer.unref(); // the timer alone never keeps the process running
}
// Queue one event and return its eventId. actorId is your own opaque id, never an email.
track(name, { actorId, properties, timestamp = Date.now() } = {}) {
if (!NAME.test(name)) throw new Error(`Invalid event name: ${name}`);
if (actorId !== undefined && !ACTOR.test(actorId)) {
throw new Error('actorId must be 8 to 128 of A-Z a-z 0-9 _ . : -');
}
if (properties !== undefined) checkProperties(properties);
const event = { eventId: randomUUID(), name, timestamp };
if (actorId !== undefined) event.actorId = actorId;
if (properties !== undefined) event.properties = properties;
this.queue.push(event);
this.trim();
if (this.queue.length >= this.batchSize) this.flush();
return event.eventId;
}
// Send everything queued. Only one flush runs at a time.
flush() {
this.flushing ??= this.drain()
.catch(error => this.log(`Ravensight flush failed: ${error.message}`))
.finally(() => { this.flushing = null; });
return this.flushing;
}
// Stop the timer and send what is left. Call it before the process exits.
async close(timeoutMs = 8000) {
clearInterval(this.timer);
this.retries = Math.min(this.retries, 1); // shutting down: two tries at most
const deadline = new Promise(resolve => setTimeout(resolve, timeoutMs).unref());
await Promise.race([this.flush(), deadline]);
if (this.queue.length) this.log(`${this.queue.length} Ravensight events were not sent`);
}
trim() {
const over = this.queue.length - this.maxQueue;
if (over > 0) {
this.queue.splice(0, over);
this.log(`Ravensight queue full: dropped the ${over} oldest events`);
}
}
async drain() {
while (this.queue.length) {
const batch = this.queue.splice(0, this.batchSize);
const later = await this.send(batch);
if (later.length) { // keep them, oldest first, for the next flush
this.queue.unshift(...later);
this.trim();
return;
}
}
}
// Send one batch. Returns the events to keep for a later flush.
async send(batch) {
const body = JSON.stringify({ events: batch }); // the same eventIds on every try
for (let attempt = 0; ; attempt++) {
const res = await this.post(body).catch(error => ({ status: 0, error }));
const answer = res.json || {};
if (answer.conflicts) {
// An eventId reused with other content: only those events were refused.
this.log('Ravensight refused reused eventIds:', answer.conflictIds);
}
if (res.status === 200 && !answer.paused) return [];
if (answer.paused) {
// The balance cannot cover more events: keep the refused ones for a later flush.
this.log(`Ravensight collection paused (${answer.reason || 'needs_funds'})`);
const refused = new Set(answer.refusedIds);
return batch.filter(event => refused.has(event.eventId));
}
const retry = res.status === 0 || res.status === 429 || res.status >= 500
|| (res.status === 409 && answer.error === 'site_changed');
if (!retry) {
// Any other 4xx would fail the same way again: log it and drop the batch.
this.log(`Ravensight refused ${batch.length} events:`, res.status, answer.error ?? '');
return [];
}
// No answer, a 5xx, a 429 or site_changed: wait, then send the same body again.
if (attempt >= this.retries) return batch;
const backoff = Math.min(this.backoffMs * 2 ** attempt, 30000);
const jittered = backoff * (0.5 + Math.random() / 2);
await sleep(res.retryAfter ? Math.min(res.retryAfter, 60) * 1000 : jittered);
}
}
post(body) {
return new Promise((resolve, reject) => {
const req = https.request(this.url, {
method: 'POST',
signal: AbortSignal.timeout(this.timeoutMs),
headers: {
authorization: `Bearer ${this.key}`,
'content-type': 'application/json',
'content-length': Buffer.byteLength(body),
},
}, res => {
let text = '';
res.setEncoding('utf8');
res.on('data', chunk => { text += chunk; });
res.on('error', reject);
res.on('close', () => {
if (!res.complete) reject(new Error('response cut off'));
});
res.on('end', () => {
let json = null;
try { json = JSON.parse(text); } catch {}
const retryAfter = Number(res.headers['retry-after']) || 0;
resolve({ status: res.statusCode, json, retryAfter });
});
});
req.on('error', reject);
req.end(body);
});
}
}
function checkProperties(properties) {
const entries = Object.entries(properties);
const safe = text => text.length <= 200 && !CREDENTIAL.test(text) && !TOKEN.test(text);
const valid = value => value === null || typeof value === 'boolean'
|| Number.isFinite(value) || (typeof value === 'string' && safe(value));
const bad = entries.find(([key, value]) => !KEY.test(key) || reserved(key) || !valid(value));
if (bad) throw new Error(`Invalid property: ${bad[0]}`);
if (entries.length > 24 || Buffer.byteLength(JSON.stringify(properties)) > 4096) {
throw new Error('At most 24 properties and 4 KB');
}
}
In your server
import { ServerEvents } from './server-events.mjs';
const events = new ServerEvents(); // reads RAVENSIGHT_SERVER_KEY
// After your own code has created the account:
events.track('account_created', {
actorId: account.id, // your own opaque id, never an email
properties: { plan: 'free', method: 'password' },
});
// Send what is left before the process exits.
for (const signal of ['SIGTERM', 'SIGINT']) {
process.once(signal, async () => {
await events.close();
process.exit(0);
});
}
The queue lives in memory, so events still waiting when the process is killed without warning are lost. For an event that must never be lost, keep it in your own database and send it from there with a stable id, as above.
Usage and billing
Each accepted server event is one event on your studio's event meter, the same as a page view or custom event from the website snippet. It draws the 1,000,000 included events a month first, then your prepaid balance at the usual events rate. Server events have no price of their own. Duplicates, conflicts, refused requests and anything sent while collection is paused are free.
When the included events are used up and the balance cannot cover
more, collection pauses before anything is stored: answers say
paused, or 429 collection_paused, until you
add funds.
Each event is stored with its name, its time, its actor's hashed id and its properties. No IP address, user agent, page, referrer, campaign, country, device or browser is stored for a server event, and never the actor id you sent. Server events are kept for 90 days. Removing the website deletes them.
Where the events show
Server events have one report of their own, for up to 90 days at a time. It lists each event name with its count, how many different actors sent it, and when it was first and last seen. Choose an event for its daily counts and actors, and one of its properties for that property's 20 most frequent values. It holds totals only, never an actor id or a single event. Read it in two places:
- In the dashboard, the Server events tab of the website's analytics: Live data > Game Website for a title, or View full website analytics on the Company website card for your company.
- Over MCP,
get_server_events, withsite:read, at the price of any MCP call.
Server events never appear in any other website report: visitors, page views, sessions, bounce rate, pages, sources, audience, Events, goals, funnels, retention, heatmaps or realtime, in the dashboard or over MCP. So a goal or a funnel cannot use a server event, and your traffic numbers stay what your visitors did. There is no link between a website visitor and an account on your server.