# How the Pug SDK delivers events reliably

How the Pug Web SDK delivers events: batches of 10 or every 5 seconds, a keepalive fetch on page hide, a localStorage queue after consent, and its retry rules.

Source: https://pug.sh/blog/reliable-event-delivery

The Pug Web SDK sends events in batches: one request once 10 are queued, or 5 seconds after the first. On page hide it drains the queue in a keepalive fetch, it keeps a consenting visitor’s queue in localStorage across reloads, and it retries network failures while dropping requests the server rejects outright. Here is each mechanism, with a link to its source.

By [Praveen Kumar](https://github.com/poluruprvn), who builds Pug. Updated November 21, 2026

Everything below is in [pug-sh/sdk-browser](https://github.com/pug-sh/sdk-browser), the repository behind `@pug-sh/browser` on npm, and each section links the file it describes. The numbers are the defaults `init()` uses when you pass no `batch` option. For autocapture, identity and consent, see [inside the Pug Web SDK](https://pug.sh/blog/web-analytics-sdk).

## Batching: 10 events or 5 seconds

The SDK queues each event and flushes when either trigger fires: 10 events are waiting (`maxSize`), or 5 seconds have passed since the first one queued (`maxWaitMs`). A flush is one `BatchCreate` request, binary protobuf over the Connect protocol, with a 5-second timeout. Both triggers are options, and `maxSize` stops at 1,000, the most events one `BatchCreate` accepts:

```
init(projectId, {
  apiKey,
  batch: { maxSize: 50, maxWaitMs: 2000 },
})
```

The queue holds at most 1,000 events (`maxQueueSize`). Past that it drops the oldest event that isn’t already in flight, with a warning, so a server that stays unreachable costs the oldest events rather than the page’s memory. The flush logic is in [batch.ts](https://github.com/pug-sh/sdk-browser/blob/main/src/batch.ts) and the request in [rpc.ts](https://github.com/pug-sh/sdk-browser/blob/main/src/rpc.ts).

## Page hide: a keepalive fetch, not sendBeacon

The hardest events to deliver are the ones fired as the page goes away: the click that navigates, the action right before a tab closes. A normal `fetch` started at that moment can be cancelled. On `pagehide`, and on `visibilitychange` when the tab goes hidden, the SDK drains every queued event into one request sent with `keepalive: true` and `credentials: 'omit'`, which the browser lets outlive the page.

That request used to be `navigator.sendBeacon`. A beacon always sends credentials, and the SDK endpoints answer CORS with a wildcard origin, since customer sites can be on any domain. A browser refuses a credentialed request against a wildcard, so it failed the preflight and dropped every page-hide flush. [Pull request #67](https://github.com/pug-sh/sdk-browser/pull/67) moved the send to a keepalive fetch, which can omit credentials and carry the API key in a header like every other call. `sendBeacon` remains only where `Request` has no `keepalive`.

Browsers allow 64 KiB of keepalive bodies in flight per page. The SDK counts its own and refuses a batch that would go over, which rolls the events back into the queue. If the browser accepts the request and it fails later, because another script spent the budget or the server answered with an error, and the page is still open, the events go back on the queue for the regular flush. The code is in [transport.ts](https://github.com/pug-sh/sdk-browser/blob/main/src/transport.ts), and the [batching design note](https://github.com/pug-sh/sdk-browser/blob/main/docs/design-notes/batch.md) walks through each failure case.

## What survives a reload

Events from a visitor who granted consent go to a queue backed by `localStorage`, with writes debounced by one second, and the next `init()` on that origin sends whatever is left in it, as long as consent is still granted. Cookieless events, which is what the SDK sends by default until a visitor chooses, go to a second queue that lives only in memory, because persisting their payloads would itself be device storage. A tab killed outright loses that memory queue; an ordinary navigation or close still sends it in the page-hide request. If `localStorage` is unavailable, the consented queue lives in memory too. Both queues are in [queue-storage.ts](https://github.com/pug-sh/sdk-browser/blob/main/src/queue-storage.ts).

## Lock, commit, rollback

Both queues share a two-phase protocol. A flush **locks** the events it takes, which hides them from the next lock; a successful response **commits** them, removing them from the queue; a failure **rolls back** the lock, so the next flush sends them again. Only one lock is held at a time, so a failed request never loses its batch, and the regular flush never resends one that succeeded.

One case can send an event twice, and the SDK accepts it. If the page hides while a flush is in flight, the page-hide request also carries the events queued behind that flush, and if the page survives, they stay queued and go out again. Losing them would be worse. A successful response can also drop events: `BatchCreate` answers with how many it accepted and why it refused the rest, and the SDK logs that as a warning, since committing the batch removes the only other trace.

## Which failures are retried

Every failed request is sorted into one of two kinds. Timeouts, network errors, and HTTP 408, 429 and 5xx answers are **transient**: the batch rolls back, and the next flush sends it again, every 5 seconds by default with no backoff and no limit on attempts. An outage costs time rather than events, until the 1,000-event queue cap starts dropping the oldest. Connect codes no retry can fix (`invalid_argument`, `not_found`, `already_exists`, `permission_denied`, `failed_precondition`, `unimplemented`, `unauthenticated`) are **permanent**, and so are HTTP 401, 403 and 404 and any other 4xx from a proxy that doesn’t answer in Connect’s format. The SDK drops those batches and logs an error rather than resend a request that cannot succeed.

For an event you don’t want to wait 5 seconds for, `immediate: true` sends it on its own at once. A transient failure puts it in the queue for the next flush, and a permanent one drops it with an error:

```
track('purchase', { amount: 49, currency: 'USD' }, { immediate: true })
```

## Never throws, never waits on the network

`track()` builds the event and returns. The network work happens later, and a failure is logged with what went wrong, never raised into your code. Before an event leaves the browser, [track.ts](https://github.com/pug-sh/sdk-browser/blob/main/src/track.ts) drops it if its name falls outside `^[a-zA-Z0-9_.-]+$`, and skips a custom property whose key starts with `$`, a prefix reserved for the properties the SDK sets, since the server would reject either. Each autocapture tracker is set up in its own try/catch, so one that fails to attach leaves the others running.

## A clean lifecycle

The transport has three states, idle, flushing and destroyed, with one request in flight at a time. `destroy()` sends whatever is still queued in one keepalive request, removes the page-hide listeners and clears the timer; a flush already in flight settles but schedules nothing after it. The SDK can then be initialized again.

## The same rules on your own server

Set `endpoint` in `init()` to a self-hosted Pug server and the batching, page-hide and retry rules above apply unchanged, since the SDK sends the same `BatchCreate` request to either. See the [SDKs](https://pug.sh/sdks) to install, and the [platform page](https://pug.sh/platform) for what happens to a batch after it arrives.

## Common questions

### Do analytics SDKs lose events when the page closes?

A plain fetch started as the page unloads can be cancelled by the browser. On pagehide, and when visibilitychange reports the tab hidden, the Pug Web SDK sends everything still queued in one fetch with keepalive set, which the browser lets outlive the page. Where the browser has no keepalive support, it falls back to navigator.sendBeacon.

### What is event batching?

Batching holds events and sends them together in one request instead of one request per event. The Pug Web SDK sends a batch once 10 events are queued or 5 seconds after the first one, whichever comes first, and both numbers are options on init().

### What happens to my events if the network fails?

A timeout, a dropped connection, or a 408, 429 or 5xx answer puts the batch back in the queue, and the next flush, 5 seconds later by default, sends it again. Events from a visitor who granted consent are kept in localStorage, so a reload does not lose them; cookieless events, the default, stay in memory. A rejection no retry can fix, such as a 400, 401 or 403, drops the batch and logs an error.

### Can the SDK slow down or crash my app?

track() returns at once and never throws: the send happens later, and a failure is logged rather than raised into your code. Each autocapture tracker is set up in its own try/catch, and if localStorage is unavailable the queue lives in memory.
