Forest Logo
search
package_2

roinsights

By @senorlawyer

Roblox

Mirrored from Wally

RoInsights Roblox SDK

Server-side Luau SDK for RoInsights, near-real-time analytics for Roblox games. Install it once on your game's servers and the dashboard shows live sessions, retention, funnels, economy, revenue, progression, custom events, version comparison, server health and script errors within 30 to 60 seconds.

  • Runs on the server. Requiring it from a client errors, and the credential never replicates. The only client code is an optional LocalScript that reports the player's device type (see Device info).
  • Every tracking call validates its input, appends to an in-memory queue and returns. Calls never yield and never throw into your game code.
  • One background thread does all network work, with one request in flight at a time.

Contents

Branching journeys

Add a Journeys field to the options in your existing RoInsights:Init() call. A connected server registers its stages under Behavior > Journeys in Studio or Live.

Journeys = {
    StoreCheckout = { { "Opened store" }, { "Viewed sword", "Viewed armor" }, { "Bought item" } },
},

After the server verifies a node's action, call RoInsights:Journey(player, "StoreCheckout", "Viewed sword"). For repeatable flows, pass one attempt ID as the fourth argument for all nodes of that visit.

Install

Pick one:

  • Creator Store (easiest). Insert the RoInsights Analytics SDK model from the Toolbox in Studio and move the RoInsights module into ServerScriptService.

  • Wally (for Rojo users). The package is server-only, so add it under [server-dependencies] and run wally install:

    [server-dependencies]
    RoInsights = "senorlawyer/roinsights@1.6.0"
    

    Map ServerPackages into ServerScriptService in your Rojo project. Use a Roblox secret for the credential, because a Config module inside the package is lost on the next install.

  • Download the .rbxm. Get RoInsights.rbxm and drag it into ServerScriptService in Studio.

Keep the RoInsights ModuleScript in ServerScriptService or ServerStorage. Anywhere else replicates to clients.

Enable HTTP

In Studio, open Home › Game Settings › Security, turn on Allow HTTP Requests, then publish. Without it, the SDK warns once and keeps retrying.

Set up the credential

Create a project in the RoInsights dashboard and copy its project credential. It starts with ri_live_. Whoever has it can send data to your project, so keep it on the server.

Init looks for the credential in this order:

  1. A Roblox secret (recommended). Add a secret named ROINSIGHTS_TOKEN on your game's Secrets page in Creator Hub, with the credential as the value and ingest.roinsights.dev as the allowed domain. The SDK reads it with HttpService:GetSecret and sends it as Bearer <secret>. It never prints or stores the value. To test in Studio, add the same secret as a local secret under Home › Game Settings › Security. Use the SecretName option to pick a different name.
  2. The Token option passed to Init.
  3. A Config ModuleScript parented to the RoInsights ModuleScript that returns { Token = "ri_live_..." }. See examples/Config.luau.

Options 2 and 3 put the credential in plain text, so the SDK refuses them unless RoInsights (and its Config child) are descendants of ServerScriptService or ServerStorage. If they replicate to clients, Init warns and stays off.

Quick start

Call Init once from a Script in ServerScriptService:

local ServerScriptService = game:GetService("ServerScriptService")
local RoInsights = require(ServerScriptService.RoInsights)

RoInsights:Init()

Then track from any server code:

RoInsights:Event(Player, "OpenedShop", { Tab = "Gems" })
RoInsights:Economy(Player, "Sink", "Coins", 250, 1200, "Shop", "SpeedBoots")
RoInsights:Progression(Player, "Campaign", "Complete", 3, "Desert")

Examples

  • Bootstrap.server.luau is a Script for ServerScriptService. It initializes the SDK and, on PlayerAdded, assigns an experiment, records the starting coins as an economy source, logs the first onboarding funnel step and sets session context. It expects the RoInsights ModuleScript in ServerScriptService and the credential in the ROINSIGHTS_TOKEN secret (or a Config module).
  • Config.luau is the optional Config ModuleScript. Parent it to the RoInsights ModuleScript and use it only when you cannot use a secret. Both modules must sit in ServerScriptService or ServerStorage, and a real credential must never be committed to a public repository.
  • Purchase.server.luau holds the handlers from the purchases guide. ProcessReceipt grants a developer product and records its PurchaseId in one UpdateAsync on the player's saved data, never trims that receipt list, and reports the purchase only after the save succeeded, so a retried receipt never grants twice. Game passes report a configured list price that a catalog lookup refreshes, never 0. tests/PurchaseDocs.spec.luau runs this file through retries and failed lookups.

API reference

All methods use colon syntax. Properties is an optional flat table of up to 24 keys whose values are strings, finite numbers from -1e15 to 1e15 or booleans (see Limits).

RoInsights:Init(Config?)

Starts the SDK. Safe to call more than once; only the first call counts. Call it from one server Script before other scripts start tracking. Calls made before Init are ignored.

OptionTypeDefaultMeaning
Tokenstring?nilProject credential, if you do not use a secret
SecretNamestring"ROINSIGHTS_TOKEN"Name of the Roblox secret to read
Endpointstring"https://ingest.roinsights.dev"Ingest API base URL. Must be https://; plain http:// is accepted only for localhost, 127.0.0.1 and [::1]
MirrorToRobloxAnalyticsbooleanfalseAlso log to Roblox AnalyticsService
TrackStudiobooleantrueSend data from Studio tests (tagged studio)
AutoTrackSessionsbooleantrueTrack player sessions automatically
DebugbooleanfalsePrint [RoInsights] logs, including dropped input
MaxQueueSizenumber5000Events held in memory before the oldest are dropped (100 to 100000)
CaptureErrorsbooleantrueReport server script errors (see Script errors)
ClientReporterbooleantrueGive each player a small LocalScript that reports device info (see Device info). Needs AutoTrackSessions

Unknown options and wrong types warn once and fall back to the default.

RoInsights:Event(Player?, Name, Properties?)

A named event. Pass nil as the player for a server-level event.

RoInsights:Custom(Player?, Name, Value?, Properties?)

A named event with a numeric value, for sums and averages. Mirrors to AnalyticsService:LogCustomEvent when mirroring is on.

RoInsights:SetOnboarding(Steps)

Declares your onboarding steps once, in order, for example RoInsights:SetOnboarding({ "Planted a seed", "Harvested", "Opened the shop" }). Up to 99 names. The SDK then reports a Joined step for every player automatically.

RoInsights:Step(Player, StepName, Properties?)

Reports that a player reached one of the declared onboarding steps. Each step is sent once per player per server, in any order. Call it for every player; the dashboard counts only each player's first session. It is sent as the Onboarding funnel, so it mirrors like Funnel.

RoInsights:Funnel(Player, FunnelName, FunnelSessionId?, Step, StepName, Properties?)

One step of a funnel. Step is an integer from 1 to 100. Pass a FunnelSessionId to tell apart repeated runs of the same funnel, such as several shop visits. Mirrors to AnalyticsService:LogFunnelStepEvent.

RoInsights:Economy(Player, FlowType, Currency, Amount, EndingBalance?, TransactionType, ItemSku?, Properties?)

A currency source or sink. FlowType is "Source" or "Sink", Amount must be greater than 0 and EndingBalance is the player's balance afterwards. Mirrors to AnalyticsService:LogEconomyEvent when EndingBalance is given, because Roblox requires it.

RoInsights:Progression(Player, PathName, Status, Level, LevelName?, Properties?)

Status is "Start", "Complete" or "Fail"; Level is an integer from 0 to 1000000. Mirrors to AnalyticsService:LogProgressionEvent.

RoInsights:Purchase(Player, Info, Properties?)

A Robux purchase. Call it from your own ProcessReceipt after you grant the item; the SDK never touches MarketplaceService.ProcessReceipt.

RoInsights:Purchase(Player, {
	Type = "DeveloperProduct",
	Name = "100 Gems",
	Robux = ReceiptInfo.CurrencySpent,
	ProductId = ReceiptInfo.ProductId,
	ReceiptId = ReceiptInfo.PurchaseId,
})
FieldTypeNotes
Typestring"DeveloperProduct", "GamePass", "Subscription" or "Other"
NamestringItem name, 1 to 64 characters
RobuxnumberRobux spent, an integer from 0 to 100000000
ProductId(number | string)?Developer product or game pass id, a positive integer. For Type = "Subscription", the subscription id string such as "EXP-1234567890" (EXP- and 1 to 20 digits)
ReceiptIdstring?Receipt or purchase id, up to 64 characters

RoInsights:SetPlayerContext(Player, Context)

Attaches flat key/value data (segments, cohorts, settings) to the player's current session. Only keys whose value changed are sent. If the event carrying a value is lost (evicted from a full queue, discarded or dropped by the ingest API), the SDK forgets that value, so the next call with the same value sends it again.

A session's context holds at most 64 keys and about 16384 bytes (the sum of each key's length and its value's text length), the same cap the ingest API applies. Changed values of keys the session already has are always sent; new keys beyond the cap are ignored, logged with Debug and warned about once. Experiment assignments count towards the same cap. Context belongs to one session: set it again after the player rejoins. Needs an active session, so it does nothing when AutoTrackSessions is off.

RoInsights:Experiment(Player, ExperimentName, Variants) -> string

Returns the player's variant and records it as session context. See Experiments.

RoInsights:Flush()

Asks the background thread to send on its next tick (within about a second). Does not yield.

RoInsights:GetStatus()

Returns a table for debugging:

FieldMeaning
ConnectedThe server holds a valid server token
ServerIdServer session id from the ingest API
QueueSizeEvents waiting to be sent, including an unacknowledged batch
DroppedEvents lost to a full queue, rejected batches or events that cannot be encoded
DroppedErrorsScript error occurrences not reported because 50 distinct errors were already waiting within about a second
RejectedEvents in a delivered batch that the ingest API rejected one by one (they failed its schema or fell outside its time window), as counted in its 2xx answer. The first rejection warns once and sets LastError
DuplicatesEvents in a delivered batch that the ingest API had already stored (an event resent after a lost answer), as counted in its 2xx answer. Normal after retries; nothing is lost. Always 0 against ingest APIs that do not report it
LastErrorLast delivery error, or why the SDK is inactive

Automatic tracking

Without any tracking calls, the SDK collects the following.

Player sessions

With AutoTrackSessions on (the default):

  • Players already in the server at Init, and every later Players.PlayerAdded, get a session_start with a new session id and the player traits below.
  • country is the two-letter ISO 3166-1 code returned by LocalizationService:GetCountryRegionForPlayerAsync, and friendsInServer counts the other players in the server the player is friends with (Player:IsFriendsWith, at most 10 checks, so the value is 0 to 10). Both lookups run in their own threads and the start waits at most 3 seconds for them; the session starts with the time the player joined either way, and leaves out a value whose lookup failed or was too slow.
TraitSource
premiumPlayer.MembershipType is Premium
accountAgeDaysPlayer.AccountAge, 0 to 100000
countryGetCountryRegionForPlayerAsync
localeThe language part of Player.LocaleId, such as en or pt (2 or 3 letters)
joinSourceteleport when Player:GetJoinData() has a SourcePlaceId, else friend when Player.FollowUserId is set, else referral when the join data has a ReferredByPlayerId, else direct. Left out when GetJoinData fails and the player did not follow anyone
friendsInServerFriends already in the server, 0 to 10
  • Players.PlayerRemoving sends session_end. Duration is computed by the server.
  • Every event for a player carries that player's session id, including events tracked while the country lookup is still running. If your code tracks a player before the SDK's PlayerAdded listener runs, the session starts on that first event.
  • Events for a player who already left are still sent, without a session id.
  • Every batch lists the ids of the sessions open at the moment it is sent (activeSessions). The server ends sessions missing from the list at their last heartbeat, so a lost session_end cannot keep a session open, and reopens listed sessions it had ended because the ingest API was unreachable for more than 10 minutes, so players who stayed through an outage keep their session.

Server health

Every batch reports the server's player count and doubles as a heartbeat, which keeps live player counts accurate even when no events happen. It also carries a server object measured since the previous request, retries included:

FieldSource
fpsHeartbeat frames divided by the time they covered
fpsMinLowest heartbeat rate of any full second in that period
memoryMbStats:GetTotalMemoryUsageMb()
dataReceiveKbps, dataSendKbpsStats.DataReceiveKbps, Stats.DataSendKbps
pingMs, pingP90MsMean and 90th percentile of Player:GetNetworkPing() across current players, sampled when the batch is built
instancesStats.InstanceCount

Each value is clamped to the protocol's range, and a value that cannot be read is left out. Without a heartbeat rate or a memory reading the whole server object is left out.

Script errors

With CaptureErrors on (the default), errors from server scripts (ScriptContext.Error) are grouped by message and script between batches. Each group becomes one error event with the number of occurrences, the time of the first one and its stack trace. Messages are cut to 300 characters, script names to 200 and stacks to 1000. Groups move into the event queue on every send attempt, retries included, and as soon as 50 distinct groups are waiting (checked about once a second), so they keep flowing while the SDK waits on a retry or the daily budget; the queue's own limit then bounds memory. New errors that arrive while 50 groups are already waiting are counted in DroppedErrors. Errors raised by RoInsights itself are ignored.

Device info

With ClientReporter on (the default) and AutoTrackSessions on, Init creates a folder RoInsightsClient in ReplicatedStorage with a RemoteEvent Report, and puts a ScreenGui named RoInsights (with ResetOnSpawn = false) holding the Reporter LocalScript into each player's PlayerGui, including players already in the server. The ScreenGui is removed when the player leaves.

The LocalScript sends two small reports per session:

FieldWhenValues
deviceAfter the camera is readyphone, tablet, desktop, console or vr
inputSame reporttouch, keyboard, gamepad or vr
screenSame reportsmall, medium or large
clientFpsAbout 60 seconds laterThe median of one-second frame rates over that minute

device is vr when VRService.VREnabled, console when GuiService:IsTenFootInterface(), phone or tablet on touch screens without a keyboard (tablet when the shorter side of the viewport is at least 600), and desktop otherwise. screen uses the shorter side of the viewport: under 500 is small, under 900 medium, otherwise large.

Client data cannot be trusted, so the server accepts one device report and one frame rate report per session, keeps only the values listed above (frame rates from 0 to 1000, rounded to 0.1) and ignores everything else, including reports from players without an open session. Each accepted report becomes a device event on the player's session. A report that arrives before session_start is held and sent right after it. Nothing on the client can error into your game or block it, and turning ClientReporter off creates none of it.

Ingest APIs older than this SDK reject device events one by one (the rest of the batch is kept), which shows up as GetStatus().Rejected and a single warning.

Privacy

The SDK sends only what is listed in this section and what your own tracking calls pass. It never reads chat, display names, usernames, friend lists or other personal data. Players are identified by Roblox UserId.

What it collects automatically:

  • Sessions: when each player joined and left.
  • Player traits on session_start: Premium, account age in days, the two-letter country or region code Roblox provides (not a location or address), the language set in Roblox, how the player joined (direct, followed a friend, teleport or invite) and how many friends were already in the server (a number only, never who).
  • Device info from the client: device type, main input, a screen size class and the median frame rate.
  • Server health and server script errors.

To collect less, set ClientReporter = false (no client script and no device info), CaptureErrors = false (no script errors) or AutoTrackSessions = false (no sessions, traits or device info).

Experiments

Experiment is deterministic: the same player always gets the same variant for the same experiment name, on every server, with no network call. It works before Init and when tracking is off, so gameplay can rely on it.

The bucket is FNV-1a (32-bit) of "<ExperimentName>:<UserId>", passed through the MurmurHash3 fmix32 finalizer, modulo the number of variants, plus one. The finalizer stops two-variant tests in different experiments from lining up. Renaming an experiment or reordering its variants reshuffles players.

The assignment is stored as session context under Exp_<ExperimentName> when the name uses only A-Z a-z 0-9 _, has at most 44 characters and does not end in _ and six lowercase hex digits (the shape of a generated suffix). Any other name is stored under Exp_, the first 37 characters of the name with every other character replaced by _, then _ and six hex digits of the name's FNV-1a hash, for example Exp_Price_A_1a2b3c. The suffix keeps names such as "Price-A" and "Price A", long names that share a prefix and non-Latin names apart; with Debug on, the key used for such a name is logged once, for the first 100 such names. If the input is invalid (no player, empty name, no variants), it returns the first variant, or "" when there is none.

local Variant = RoInsights:Experiment(Player, "ShopLayout", { "Control", "Grid" })

Mirroring to Roblox Analytics

Set MirrorToRobloxAnalytics = true to also log Custom, Funnel, Economy and Progression calls to Roblox's built-in AnalyticsService. Each call is protected and runs after the event is queued, so a mirroring failure never affects RoInsights data. Roblox accepts three custom fields; the SDK fills CustomField01 to CustomField03 from the first three properties in sorted key order, formatted as "Key - Value". Event and Purchase are not mirrored: Roblox caps custom event names and already records purchases.

Limits

These match the ingest protocol. Input that breaks them is fixed when possible and dropped otherwise; with Debug on, each call logs one line describing what was dropped.

FieldLimit
Names (Name, FunnelName, StepName, Currency, TransactionType, ItemSku, PathName, LevelName, purchase Name)1 to 64 characters; leading and trailing whitespace (including Unicode spaces such as U+00A0 and U+3000) is removed, a name that is only whitespace is dropped and longer names are truncated
Property count24 per event; extra keys are dropped in sorted key order
Property keysMatch ^[A-Za-z][A-Za-z0-9_]{0,47}$
Property valuesStrings up to 200 characters (truncated; an empty string is allowed), finite numbers from -1e15 to 1e15, booleans. Nested tables are dropped
FunnelSessionId, ReceiptIdUp to 64 characters
Funnel StepInteger from 1 to 100
Custom Value, economy EndingBalanceFinite number from -1e15 to 1e15
Economy AmountGreater than 0 and at most 1e15
Progression LevelInteger from 0 to 1000000
Purchase RobuxInteger from 0 to 100000000
QueueMaxQueueSize events; when full the oldest events other than session_start and session_end are dropped first and counted in Dropped
Active sessionsUp to 1000 session ids per batch; with more open sessions the list is left out
Player context64 keys and about 16384 bytes per session, Experiment keys included; new keys beyond that are ignored

Lengths are counted the way JavaScript counts them (UTF-16 code units), and truncation never splits a character. NUL characters are removed from all text because the ingest API cannot store them.

Delivery, retries and shutdown

The background thread connects with the project credential, receives a short-lived server token, then sends batches:

  • every flush interval (30 seconds unless the server says otherwise), even with no events;
  • sooner when 200 or more events are waiting (at most every 2 seconds), when a batch was full, or after Flush().

Batches respect the server's event and byte limits. A failed batch keeps its id, so the server discards duplicates when a retry repeats one that actually arrived. Every request passes a 15 second Timeout to HttpService:RequestAsync, so a hanging ingest API cannot stall the background thread; a request that times out is retried like a network error. If Roblox refuses the Timeout option, the SDK warns once and sends requests without it.

ResponseWhat the SDK does
400Usually means the SDK and the ingest API run different versions, for example during a rollback. Warns once, keeps the batch and resends it after 16, 32 and 60 seconds; from the third attempt on it leaves out server and activeSessions, the envelope fields added after protocol 1.0. After four 400 answers (about 2 minutes) the batch is dropped and counted in Dropped. A batch whose envelope cannot be encoded as JSON is dropped at once
401Reconnects, then resends the same batch
403 on eventsStops sending until the server restarts
413Splits the batch in half and sends both halves with new ids
429Waits Retry-After seconds, then resends the same batch
429 allowance_exceededThe project sent more events per minute than its ingest allowance, which follows the game's player count. Warns once, keeps the batch and waits Retry-After seconds, at least 5 seconds and at most 5 minutes, before resending it
429 budget_exhaustedThe project's daily safety cap is used up. Warns once, keeps the batch and waits Retry-After seconds, at least 1 minute and at most 1 hour, before resending it. Meanwhile it holds every queued event and sends a heartbeat without events every flush interval, so the server and its sessions stay live in the dashboard; a heartbeat the API refuses changes nothing
5xx or network errorRetries after 2, 4, 8 ... up to 60 seconds

Connect failures back off the same way. A rejected credential, an unavailable project or a universe mismatch warns once and retries every 5 minutes. A server revoked in the dashboard can never reconnect under its job id, so a server_revoked answer to connect stops the SDK until the server restarts, like a 403 on events.

On shutdown the SDK's game:BindToClose handler ends every open session, sends what it can within 25 seconds (Roblox allows 30) and then disconnects the server. Request timeouts shrink to fit that budget, so a slow or hanging ingest API cannot hold shutdown longer.

Troubleshooting

Call RoInsights:GetStatus() from the server console, or set Debug = true.

Message or symptomFix
HTTP requests are disabledTurn on Home › Game Settings › Security › Allow HTTP Requests and publish
no credential foundAdd the ROINSIGHTS_TOKEN secret, or use the Token option or a Config module
refusing to use a plain-text token: ... replicates to clientsMove RoInsights to ServerScriptService or ServerStorage, or use a secret
not a project credentialUse the ri_live_ project credential, not a server token
belongs to a RoInsights project configured for another universeUse the credential of the project for this game, or change the project's universe
the project credential was rejectedThe credential was revoked or its rotation grace period ended. Create or rotate a credential under Settings › SDK & credentials and update the secret
this server was revoked in the RoInsights dashboardSomeone revoked this game server on the dashboard's servers page. The SDK stops until the server restarts
this project sends more events per minute than its ingest allowanceThe project went over its per-minute allowance. The SDK keeps the events and sends them more slowly; send fewer events per player
this project's daily ingest budget is used upThe project reached its daily event or byte cap. The SDK keeps queueing, keeps sending heartbeats without events and retries hourly until 00:00 UTC; send fewer events
the ingest API rejected a batch as invalidThe SDK and the ingest API probably run different versions. The SDK retries for about 2 minutes; if it keeps happening, update the SDK or check the Endpoint
the ingest API rejected N of M eventsSome events failed the ingest schema or fell outside its time window. Turn on Debug and compare your calls with Limits
player context holds at most 64 keysSet fewer distinct context keys per session; changed values of existing keys still arrive
the SDK is server-onlyRequire RoInsights from a server Script, not a LocalScript
Nothing arrives from StudioTrackStudio is false, or Studio has no local secret. Studio data is tagged studio in the dashboard
Dropped keeps growingThe ingest API is unreachable, or you send more than the queue holds. Raise MaxQueueSize or send fewer events

Design notes

The source carries no comments; the reasoning behind its less obvious choices lives here.

Module layout

ModuleRole
initPublic API. Validates arguments and builds events. Every public call runs inside one pcall boundary, so a bug can never throw into game code. A rejected call returns a reason, logged only with Debug
RuntimeThe only module that reads Roblox globals. It packs services, the clock, the scheduler and server identity into an Env table that every other module receives, which lets the Lune suite swap all of them for fakes
SettingsMerges Init options with the defaults. Unknown keys and wrong types fall back to the default and warn once, so a typo never silently changes behaviour
CredentialCredential resolution and the replication check
ValidateCheap sanitizers that run on the caller's thread
QueueBounded FIFO that evicts the oldest non-session event when full, because recent activity matters more to a live dashboard than a backlog the server may already treat as stale, while one lost session_start or session_end distorts a whole session. Evicted slots are skipped by Peek and Pop, and a scan cursor that only moves forward keeps eviction amortized O(1)
BatchCuts request-sized batches off the queue
TransportThe HTTP boundary. Every request runs in one protected call and returns a result with a status code; status 0 means the request never completed
AgentPlayer sessions, the queue and the single background thread that connects, sends, retries and shuts down
HealthHeartbeat rate counters and the per-batch server snapshot
ErrorsGroups ScriptContext.Error reports between batches
TraitsReads locale, joinSource and friendsInServer for a session, each behind pcall
ClientReporterCreates the report remote, gives each player the client LocalScript and parses client reports against fixed value lists
Client/ReporterThe LocalScript that runs on each player's client and reports the device info
MirrorOptional copy into Roblox AnalyticsService
ExperimentDeterministic variant assignment
UuidTurns a random Roblox GUID into a time-ordered UUID version 7
TypesShared type contracts, including Env

Credential resolution and replication

Init takes the first credential it finds: the Roblox secret named by SecretName, then the Token option, then a Config ModuleScript that is a child of RoInsights. A secret never exposes its value to Luau and is sent as Secret:AddPrefix("Bearer "), so it is safe wherever the module lives. If a Config module that replicates to clients still exists next to a secret, the SDK uses the secret and warns that the module leaks.

A plain-text token is accepted only when RoInsights is a descendant of ServerScriptService or ServerStorage, and for the Config module, only when that module is too. Any other location replicates to clients and would hand the credential to every player, so Init refuses, warns and leaves the SDK off. Tokens are trimmed and must match ^ri_live_[A-Za-z0-9_-]+$; server tokens (ri_srv_) are rejected. No message, log or status ever contains a token.

Requiring the module where RunService:IsClient() is true and RunService:IsServer() is false raises an error. Both are checked because Studio's Run mode reports true for both.

Experiment hashing is a public contract

The variant index is fmix32(FNV1a32("<ExperimentName>:<UserId>")) % #Variants + 1, where the user id is formatted as an integer. FNV-1a alone keeps the parity of the input bytes in its lowest bit, so two-variant experiments would line up with each other; the MurmurHash3 fmix32 finalizer removes that correlation. Products are computed in 16-bit halves because a 32 x 32-bit product does not fit exactly in a double. Changing any part of this reshuffles every running experiment, so it must stay fixed across SDK versions. The test suite pins reference values computed independently.

Batching and size estimation

A batch is cut by adding events from the head of the queue while both limits from the connect response hold: maxEventsPerBatch, and an estimated size of 256 bytes reserved for the envelope plus each event's JSON length and one byte for the separating comma. Each event is encoded once when it is considered, so the estimate is exact for the events and conservative for the envelope. The batch keeps those JSON strings and the request body is the encoded envelope with the events array spliced in, so no event is encoded twice and a retry only encodes the small envelope again. The active session list also needs room: 39 bytes (a quoted UUID and a comma) for every open session plus 10 spare ids, so players who join before a retry rarely push a batch over the limit.

The active session list is built when a request is sent, not when its batch is cut, so a retry reports who is in the server now. Sessions whose session_start is still waiting for the country lookup are listed too; the server ignores ids it does not know yet.

An event that cannot fit into any request on its own, or cannot be encoded as JSON, is discarded and counted in Dropped, so it can never block the queue. When a batch leaves events behind because it hit a limit, the next batch goes out on the following tick instead of waiting for the flush interval. A 413 response still splits the batch in half with new batch ids.

The background thread wakes once per second. Public calls only set fields and append to the queue, which is why Flush() takes effect within about a second and why at most one request is ever in flight.

Time-ordered ids

Event, session and batch ids are UUID version 7 (RFC 9562): the first 48 bits are the Unix time in milliseconds and the remaining 74 random bits come from HttpService:GenerateGUID, whose version 4 variant bits are kept. The ingest API stores events under (project, id), so ids that grow with time append to the end of that index instead of landing on random pages, and ties in time-ordered queries break in generation order. The ids reveal only the time the event already carries as t. The Studio job id fallback stays a random version 4 GUID. Any UUID version is valid in the protocol, so older SDKs keep working.

Shutdown budget

Roblox gives game:BindToClose handlers 30 seconds. The SDK's handler ends every open session, marks the agent as closing and waits, polling every 0.1 seconds, for at most 25 seconds. The background thread then drains: it reconnects if needed, sends batches and honours retry waits, but stops 3 seconds before the 25 second deadline to leave time for the disconnect request. Each request's Timeout is the smaller of 15 seconds and the whole seconds left before that point, and draining stops when less than one second is left; the disconnect gets at most 3 seconds. A request started just before shutdown can still take its full 15 seconds, after which draining uses what remains. Events that could not be sent in time are lost and remain visible in QueueSize. After a 403 the server is halted and shutdown returns immediately without a disconnect.

Lazy session start

Your own PlayerAdded handlers can run before the SDK's and already track the player. The first event for a player without a session therefore starts the session, and the SDK's own PlayerAdded handler then reuses it, so each join produces exactly one session_start. A player who has left never gets a new session: events reported during or after PlayerRemoving, such as a save on leave, are sent with the user id but without a session id. Sessions are not started while the server is shutting down.

Country lookup and session ordering

GetCountryRegionForPlayerAsync yields, so the session is created at once (its id and join time are fixed then) and only its session_start event waits. A lookup thread and a 3 second timer race to send it; whichever finishes first sends it with the original join time, and the other does nothing. If the player leaves first, PlayerRemoving sends session_start without country immediately and session_end right after, so the start always precedes the end in the queue. The same happens for every open session when the server shuts down. Player events tracked while the lookup runs carry the session id but can be queued ahead of their session_start; the server joins them by session id, not by order.

Device reports

The device info is the only data that comes from the client, so the server treats it as hostile input. The remote handler runs inside pcall, reads only the four known fields, keeps a string only when it is one of the listed values and a frame rate only when it is a finite number from 0 to 1000, and flips a per-session flag for each of the two report kinds before looking at the values. A flood of remote calls therefore costs one table lookup each and can only ever spoil that player's own device info. Reports are tied to the sender's session, never to ids in the payload.

The LocalScript is cloned from the model by the server instead of living in StarterPlayerScripts, so installing the SDK stays a single drag into ServerScriptService and a server with ClientReporter off runs no client code at all. The ScreenGui keeps ResetOnSpawn off so a respawn does not run the script again.

Server health cost

The Heartbeat handler only adds to four numbers on an existing table: frames and elapsed time for the batch, and the same pair for the current second. It allocates nothing and reads no services. fps is frames divided by elapsed time, the true average rate; averaging 1 / delta per frame would let a few very short frames inflate it. fpsMin closes a one-second window each time the second's elapsed time reaches one second. Everything else (memory, network, instances, ping) is read once per request inside pcall. Every request, including each retry of a batch and both halves of a 413 split, takes a new snapshot, so each one reports the interval since the previous request and samples never overlap. A retry the server already committed is answered as a duplicate before its heartbeat is stored, so no interval is counted twice.

Error capture safety

The ScriptContext.Error handler runs inside pcall and only updates an in-memory table, so it cannot raise an error of its own and start a loop. Errors are ignored when the reporting script is the RoInsights module or one of its children, or when the stack trace contains a line from it (<RoInsights path>. or <RoInsights path>,), so a fault in the SDK is never reported back into the SDK. Groups are keyed by script path and the message normalised exactly like the server's error fingerprint (normalizeErrorMessage in the API's ingest/store.ts, which this must keep matching): UUIDs become <id>, quoted text <text>, 0x hex numbers <hex> and other numbers <n>, and whitespace runs collapse to one space. Player 12 has no data and Player 13 has no data therefore share one group, which reports the first raw message as its sample. The 50-group cap bounds memory when a script fails with a genuinely different message every frame.

Development

This section is for working on the SDK itself. Games install the SDK from one of the channels in Install.

Tools are pinned in rokit.toml (Lune, StyLua, selene, Wally, luau-lsp). From sdk/roblox:

rokit install
stylua --check src tests scripts examples
selene src tests scripts
lune run scripts/test
lune run scripts/build
  • lune run scripts/test [filter] runs every tests/*.spec.luau file, each test in a fresh fake world, prints a summary and exits with status 1 on any failure. The optional filter matches test names. RealClock.spec runs the agent on Lune's real clock and scheduler for about 9 seconds to catch unit mistakes in timers; set ROINSIGHTS_SKIP_REAL_CLOCK=1 to skip it during quick local runs. CI runs it.
  • lune run scripts/build writes dist/RoInsights.rbxm: a ModuleScript named RoInsights built from src/init.luau, with one child ModuleScript per other src file, a Client Folder holding the Reporter LocalScript from src/Client/Reporter.client.luau, and a Version attribute. It reads the file back and checks every child before exiting, and fails when the versions in wally.toml and src/Settings.luau disagree. No Rojo is involved.
  • The same command also stages a package layout in dist/wally/, with a generated default.project.json that maps src/ to a single ModuleScript. It is the layout that gets published to Wally.

Strict type checking with luau-lsp needs the Roblox definitions file and a sourcemap, which scripts/sourcemap.luau writes without Rojo so luau-lsp can resolve script.Parent requires:

curl -sSfL -o globalTypes.d.luau https://raw.githubusercontent.com/JohnnyMorganz/luau-lsp/main/scripts/globalTypes.d.luau
lune run scripts/sourcemap
luau-lsp analyze --platform=roblox --definitions=globalTypes.d.luau --sourcemap=sourcemap.json src

The tests compile the real src files with @lune/luau against fake Roblox globals, a virtual clock and a cooperative scheduler, so timing and retry behaviour run without real sleeps. The fake RequestAsync can delay a path on the virtual clock (World:Latency) and honours the request's Timeout, which is how the shutdown tests prove that a hanging endpoint cannot outlast the budget.

License

MIT. See LICENSE.

Package Details

Install command (Click to copy)


Version

1.6.0

License

MIT

check_circle

Safe for commercial use

Automated license review — not legal advice.