Swan SDK
Concepts

Event model

How events are tracked, queued, batched and shipped — and how the typed e-commerce events relate to plain custom events.

The SDK's event model is offline-first and append-only. Every call to track, customEvent or a typed e-commerce helper writes to a local SQLite queue first, then flushes to the Swan backend on a background scheduler. If the network is down the queue grows; when connectivity returns it drains with exponential-backoff retry.

Event families

FamilyExamplesWhen to use
Lifecycle (auto)sessionStarted, sessionEnded, appOpened, appBackgroundedEmitted automatically by the SDK; you don't call these
Screen trackingSwanEvents.screen("ProductDetail", attrs)One call per screen view
E-commerce (typed)productViewed, productAddedToCart, checkoutCompleted, orderCompleted, search, categoryViewedPageUse these when applicable — they emit a canonical schema the campaigns engine knows
CustomSwan.customEvent("clickedHero", { variant: "A" })Anything domain-specific

The typed e-commerce helpers exist because the Swan backend's campaign engine recognises those event names + payload shapes and can target / segment on them. A free-form customEvent("productViewed", ...) will land but won't be picked up as e-commerce data — use the typed helper.

Super-properties

Some attributes apply to every event: country, currency, business unit and current screen. Set them once and every event tracked afterwards carries them, without you passing them per event.

Country, currency and business unit are kept across launches (across page loads on Web) until you change them, and they stay through login and logout. An empty string clears one. So events the SDK sends before your code runs on a later launch — appLaunched above all — carry the values you set last time.

When you change a value (for example the customer switches country or business unit), every event tracked after the change carries the new value — including appLaunched on the next foreground and on later launches. An event keeps the values it had when it was tracked, even if it is sent later (queued while offline, or waiting for the next batch). On Web, a change made in one tab applies to your site's other open tabs too.

On the very first launch, set them before the SDK sends its first event, so appLaunched carries them too: before init on Android and iOS, right after getInstance on React Native, and before your first event on Web. If you only learn them later (for example from a server call), set them then: events from that point on carry them, and so does every later launch.

The current screen name is not kept: set it as screens change.

// Before init, so the first appLaunched carries them.
Swan.setCountry("AE")
Swan.setCurrency("AED")
Swan.setBusinessUnit("loyalty-app")
Swan.init(
    context = applicationContext,
    appId = "your-app-id",
)

// As screens change.
Swan.setCurrentScreenName("ProductDetail")
// Before initialize, so the first appLaunched carries them.
Swan.shared.setCountry("AE")
Swan.shared.setCurrency("AED")
Swan.shared.setBusinessUnit("loyalty-app")
Swan.shared.initialize(appId: "your-app-id")

// As screens change.
Swan.shared.setCurrentScreenName("ProductDetail")
import SwanSDK from '@loyalytics/swan-react-native-sdk';

const sdk = SwanSDK.getInstance('your-app-id', {});
// Right after getInstance, so the first appLaunched carries them.
sdk.setCountry('AE');
sdk.setCurrency('AED');
sdk.setBusinessUnit('loyalty-app');

// As screens change.
sdk.setCurrentScreenName('ProductDetail');
import { Swan } from '@loyalytics/swan-web-sdk';

Swan.setCountry('AE');
Swan.setCurrency('AED');
Swan.setBusinessUnit('loyalty-app');
Swan.initialize('your-app-id', { production: true });

// As screens change.
Swan.setCurrentScreenName('ProductDetail');

Batching and flush

TriggerWhen
Time-basedEvery 30s while events are in queue
Size-basedWhen the pending count reaches the batch size (default 10)
LifecycleApp foreground / background transitions
ManualSwan.flush() for tests / forced uploads

A network outage alone never causes an event to be dropped. If a send gets no answer (offline, timeout) or the server is briefly unavailable (HTTP 408, 429 or 5xx), the events stay queued — on the device, across app restarts — and are retried with exponential backoff (2s, 4s, 8s … up to 60s; a Retry-After from the server is honoured), and again as soon as the network comes back. A response that doesn't confirm an event — no entry for it, or no readable list of results — is treated the same way: the event stays queued and is retried, neither counted as rejected nor treated as sent. The queue is still bounded: an event that is still unsent 7 days after it was tracked is dropped, and the queue keeps at most 5,000 events (see below). While the server has asked the SDK to wait (Retry-After), no flush sends queued events, whatever starts it — including flush().

If the server answers HTTP 5xx three times in a row for the same batch of several events, the SDK resends them one at a time, so one event the server can't process doesn't hold up the events queued behind it. If the first single send fails, the SDK sends the newest queued event on its own to check whether the server is up: if it is, it carries on past the failing events; if not, it treats it as an outage and stops until the next retry. A batch the server refuses as a whole with an HTTP 4xx (including 413, too large) is split and resent right away, so only the event the server refuses on its own is counted as rejected. On the Web, a single request carries at most 10 events and at most 100 KB.

An event is dropped only when:

  • the server rejects it outright (any other HTTP 4xx, or a per-event failure in the response) three times. An event that already failed on its own in an earlier attempt counts as rejected when it gets HTTP 5xx on its own twice more while newly queued events are being accepted, over two attempts in a row — and no more such events are counted than newly queued events were accepted, and only when the attempt before also had newly queued events accepted. Failed sends during an outage never count, or
  • it is still unsent 7 days after it was tracked, or
  • the queue is full (5,000 events) and the oldest events make room for new ones.

Either way the SDK logs how many events it dropped and why.

Sessions

A session is the time between an app foreground and the next 20-minute inactivity gap. The SDK manages this transparently via the platform's lifecycle observer (Android ProcessLifecycleOwner, iOS scene lifecycle, RN AppState).

Anything you track inside a session inherits the sessionId, so you can reconstruct a user journey downstream without doing client-side session math.

Check the queue and the session

To check that events are being queued, or to match a session with what you see downstream, read the queue size, the current session and the device's identifiers once the SDK is initialised.

Read them when you need them, not on a timer. On Android, iOS and React Native, reading the current session counts as activity, so polling it keeps the session open past the 20-minute inactivity gap.

val queued: Int = Swan.getQueueSize()
val session: String? = Swan.getCurrentSessionId()
val info = Swan.getDeviceInfo() // null until the SDK is initialised
// info?.identifier, info?.generatedCDID, info?.currentCDID, ...
let queued = Swan.shared.getQueueSize()
let session = Swan.shared.getCurrentSessionId()
let info = Swan.shared.getDeviceInfo()
const sdk = SwanSDK.getCurrentInstance();
const queued = await sdk?.getQueueSize();
const info = await sdk?.getDeviceInfo();
// info: { deviceId, generatedCDID, currentCDID, identifier?, ... }
const swanId = await sdk?.getSwanIdentifier();
// the signed-in customer's identifier, otherwise the anonymous one
const queued = await Swan.getQueueSize();
const info = await Swan.getDeviceInfo();

On the web, each open tab of your site keeps its own queue, and every event is sent once, by one tab. Swan.getQueueSize() counts the current tab's events. Events left unsent by a page load that has ended (the tab was closed or reloaded) are taken over by the next page load or another open tab and sent from there — right away when the page was closed normally, otherwise about two minutes later. They are added to the queue a moment after Swan.initialize(...) returns; Swan.flush() waits for them. When the page is hidden or closed, the SDK sends its queued events with a request the browser completes even after the page is gone; the next page leaves those events alone for five minutes and sends them again only if the closed page could not see that request succeed. If browser storage is full, every queued event is kept in memory and stored again as soon as there is room; only the 5,000-event limit drops events.

On this page