Mobile Design Rounds
Case studyAndroidiOS14 min read

Design an analytics SDK (Android and iOS): queue, batching, retry and consent

Last reviewed . Drafted with AI assistance. Checked against official documentation where noted (how this is checked). Part of: The five-step method · Offline-first guide · Staff-level guide.

Build it. The database schema, API, code and platform limits for an analytics SDK are on a separate page: Build it: an analytics SDK on Android and iOS (18 min read).

How to read this. This page is a 45-minute round (the length I assume), in the order I would spend it. The code is in the build guide. The follow-up questions are my reconstruction from public prep material, not transcripts of real rounds.

TL;DR. My answer: the SDK (a code library that other apps add) promises to take the event, not to deliver it. It saves the event to disk and sends it later in a batch that never changes. It deletes the batch only after the server says yes. The server removes repeats. The SDK never blocks or crashes the host app. On iOS the same design holds: an actor is the single writer, a background URLSession upload can survive suspension, and the SDK ships its own privacy manifest.

Patterns in this round.

More in design patterns in mobile rounds.

Free: one follow-up round a week. A short interview question with a weak and a strong answer, by email. You also get the cheat sheet.

1. Scope and constraints (minutes 0 to 4)

In short: Say what the SDK promises, keep money out of it, and leave some topics for later.

A prompt I would expect: "Design an analytics SDK for mobile apps." It is vague on purpose. I ask five questions, with a default for each:

  • Who uses the SDK? Several host apps (the apps that contain it), each with a start-up budget.
  • Who reads the data? A data team that wants counts and funnels (the steps users take, in order). A repeat is cheaper than a lost event.
  • Which privacy rules apply? EU and US state rules, so the SDK must stop collecting and delete data on request.
  • What does the server accept? A batch endpoint, an event ID and a batch ID.
  • Must any number be exact, such as money? No. The server keeps its own record of purchases.
In scopeOut of scopeParked (left for later)
Public API, event record, disk queueThe server pipeline, dashboardsAuto-capture of taps and screens
Batching, retry, two timestamps, drop policyCrash reportingA host with a second process
Consent gate, privacy filesRemote settings, samplingErasing data the server holds
Test and debug toolsOld SDK versions in use
What the phone doesRequirement at riskDeep dive
Kills the app at any timeAn accepted event survives2, 3
Limits background workEvents arrive in a reasonable time4.1
Loses the network, and has a small batteryNo lost batch, no repeat counted twice, few requests2, 4.1
Lets the user say no, and change their mindNothing kept without consent4.2

Your decision. Finance says: "Count purchases from your analytics events." Do you accept, refuse, or keep the record on the server?

First idea, and why it fails. Accept, because the data is already there. But events are lost when the app is killed, repeated when a send is retried, and deleted when the user opts out. Money counted from them would be wrong.

What I would say.

Say this. "Events can be lost or repeated. Money cannot. So the server keeps the record of purchases, and events are for analysis only. If finance wants a check, we compare the two and look at the gap."

I reject using events as the record.

The follow-up question I expect:

"Then what are events good for?"

Trends and funnels. A small error does not change those decisions.

45-minute plan

MinutesStepWrite down by the endCut if behind
0 to 4Scope and constraintsThe promise, the money boundaryThe phone table
4 to 14Data and contractsEvent record, IDs, timesThe numbers table
14 to 22Client structureWho owns the queue and the workerThe iOS note
22 to 40Make the hard part workFixed batch and retry, consentThe second follow-up question
40 to 45Break it, ship it, roll it backFailure rows, release factsThree rows only

2. Data and contracts (minutes 4 to 14)

In short: An accepted event is on disk, has two IDs and two times, and the server can safely see it twice.

Your decision. The host calls track on the main thread (the thread that draws the screen). Does track promise delivery, a place on disk, or only that the SDK took the event?

First idea, and why it fails. Send the event at once with a network call and report the result. This fails when the phone is offline, or when the app is killed before the answer arrives.

What I would say. track promises only that the SDK took the event. It returns nothing to wait on. The event reaches disk within about one second. I reject sending each event as it happens.

The follow-up question I expect:

"The app is killed before the commit. What did you lose?"

At most one commit group (events written to disk together in one transaction). I document it.

  • At 5 events a second, that is about 5 events.
  • A count rule of 20 events caps a sudden spike.

Your decision. The device clock can be wrong. Which time do you store and send?

First idea, and why it fails. One timestamp from the device clock. It fails when the user sets the clock back a year.

What I would say. Each event stores the device time and a monotonic offset (time since boot, which the user cannot change). On Android that is SystemClock.elapsedRealtime, which keeps counting in sleep. On iOS I use a clock that also keeps counting in sleep, and I declare its use in the privacy manifest (see 4.3). The batch carries its send time. The server adds its receive time and estimates the true event time. I reject trusting the device clock.

The follow-up question I expect:

"What if the user changes the clock while the app runs?"

The offset keeps the order inside one run. Across runs, a counter that belongs to the install keeps the order.

The contract has four lines. The build guide has the fields.

  • An event gets a random ID when track is called.
  • A batch gets an ID the first time its events are picked. It never changes.
  • The server ignores any batch ID or event ID it has seen.
  • The event keeps the identity it had at track time.

My own assumptions, not measurements:

AssumptionArithmeticWhat it settles
A busy session: 150 events of 300 bytes. Gzip (compression) cuts the body to a quarter45 KB, or about 11 KB with gzip. 150 requests, or 3 batches of 50Send batches, with shared data once per batch
Peak rate is 5 events a second. The writer saves every 1 second or every 20 eventsAt most 5 events wait in normal use, 20 in a spike. That is 1 transaction a second, not 5The loss window is a number I can state
On the phonedevice time + offset since bootthe offset keeps order in one runIn the batchthe batch carries its send timeOn the serveradds its receive time, then estimatesthe true event time
Each event keeps a device time and an offset since boot, the batch adds its send time, and the server adds its receive time to estimate the true time.

3. Client structure (minutes 14 to 22)

In short: The SDK owns its queue and its worker. It does not depend on the host's screens or app object.

Your decision. Who owns the disk queue and the work that sends it? The host's app object, a screen, a service, or an engine that the SDK creates and owns?

First idea, and why it fails. Start the SDK in a content provider (an Android component that runs at app start) so hosts write no code. App Startup says these are expensive to start and start in no set order (App Startup). So the SDK may start before consent is known. Also, work in a caller's scope ends with its screen, and the flush (sending queued events) stops.

What I would say. The host calls init once. It does no disk work. The SDK creates one engine with its own scope (the lifetime of its work), so its work can live longer than any screen (data layer). I reject three other owners:

  • The host's ViewModel, which ends with its screen.
  • A service, which adds a second lifetime for the host to manage.
  • A global singleton that the host does not control.

The follow-up question I expect:

"The host has a widget in a second process. Where does one writer break?"

One writer holds only inside one process. Give the store one owner process, or use SQLite locks with short transactions. This returns as follow-up 3.

trackwritetriggersreadbatchPOSTApp codeany threadPublic APItrack, identify, flushValidate + consentno consent: dropDurable queuesingle writer, on diskFlush policycount, time, backgroundBatcherbatch id, event idsUploaderbackoff + retryServerdedupes batchesApp codeany threadtrackPublic APItrack, identify, flushValidate + consentno consent: dropwriteDurable queuesingle writer, on diskFlush policycount, time, backgroundtriggersBatcherbatch id, event idsServerdedupes batchesPOSTUploaderbackoff + retry

More links

  • Durable queue to Batcher: read
  • Batcher to Uploader: batch
Analytics SDK architecture: events pass validation and a consent gate into a durable queue; a flush policy triggers a batcher and uploader that retry with backoff.

On iOS, an actor (a Swift type that runs one task at a time) is the writer, and an async stream is the inbox. Three rules:

  • No disk or network work on the caller's thread.
  • Every entry point catches errors.
  • The SDK keeps only the application context, never an activity.

4. Make the hard part work (minutes 22 to 40)

In short: Fix each batch with an ID and never change it. Check consent before anything is saved.

4.1 Batches, retry and background limits (minutes 22 to 31)

Your decision. The server is slow, or does not answer. How do you resend so that nothing is lost and nothing is counted twice?

First idea, and why it fails. Delete the events when you send them. On a retry, pick the newest events again. This fails when the response is lost. The server saved the first batch, the client sends a different one, and some events are counted twice.

What I would say.

Say this. "The first time I pick events, I give them a batch ID and record which events belong to it. A retry sends the same batch, even if newer events arrived. I delete it only when the server says yes. If the server has seen the ID, it skips the batch."

Captureevent gets an IDQueue on diskabout 1 s to diskServerskips a batchID it has seenBatchgets an ID onceand keeps it123461 track(): the event gets an ID and is queued.2 A batch of events gets its own ID.3 Upload: the server keeps it, no answer returns.4 The retry sends the same batch and ID.5 The server skips the repeat and says yes.6 Only now is the batch deleted from the queue.
Events are queued on disk and sent as a batch with its own ID. If no answer comes back, the same batch is sent again. The batch is deleted only after the server says yes.

A permanent error, such as a 400, deletes the batch and counts it. A bad write key (the secret the SDK sends with data; 401 or 403) keeps the batch. Retries use backoff (wait longer after each failure) and a random delay. I reject picking events again on a retry.

The follow-up after that: "The app is killed after the send, before the answer. What happens at the next launch?"

  • The batch ID and the list of its events are written to disk before the first send. A restart reads them back.
  • The retry sends that same batch with that same ID. The server has seen the ID, so it skips the batch and says yes.
  • Do not make a new batch from the queue at launch while a fixed batch is still waiting. A new ID looks like new events, and the server counts them twice.

The follow-up question I expect:

"The app is rarely opened. How does the queue empty?"

I flush when the app goes to the background and at the next launch. WorkManager (Android's scheduler for work that survives restarts) is only a backup. When the app goes to the background and the queue is not empty, I also enqueue one unique one-time job that needs a network. A periodic job cannot run sooner than 15 minutes. I promise no delivery time.

  • Periodic work repeats at most every 15 minutes, and can be delayed (define work).
  • A rarely used app is put in a low App Standby bucket. Its jobs may run only about once a day (App Standby Buckets).
  • So the next foreground flush is the real recovery.

When the disk is full, I drop the oldest events and count them. This keeps the newest data, and I document the choice.

Your decision. Where does the SDK check consent: when the event is created, when it is saved, or when it is sent?

First idea, and why it fails. Save everything and filter at upload. This fails when the user says no after events are on disk.

What I would say. Consent is granted, denied or unknown, and unknown acts as denied. The gate sits at track, before the inbox. Opt-out stops collection, deletes the queue and cancels uploads. The host owns the prompt, and the SDK reads the host's choice, as Google asks (SDK safety). I reject filtering at upload.

One trade-off: events before the user answers (app open, onboarding) are lost if I write nothing. Two options:

  • Drop them. This is the safest and simplest, and it is my default.
  • Keep a small in-memory buffer. It is bounded, never written to disk, and thrown away if the user says no.

Say this. "Short answer first: nothing is written before consent, so there is nothing to filter later. Now back to the fixed batch, which keeps a retry from counting an event twice. Next I show the status codes."

The follow-up question I expect:

"What does iOS require from the SDK itself?"

Its own privacy manifest (a file that lists the data and the system APIs the SDK uses) (Apple).

  • It is needed if the SDK uses a required reasons API (a system API that Apple lists), collects data, helps the app collect data, or contacts tracking domains.
  • Requests to tracking domains fail without permission. I keep the batch and stop retrying fast. I try again at the next launch, or when the tracking permission changes. A hot retry loop would only waste battery.

4.3 Where iOS changes the design

The design is the same: one writer, a fixed batch, consent at track. The Swift sketch is in the build guide.

The writer and the clock.

  • An actor is the only writer. An AsyncStream with a bounded buffer is the inbox, and it drops the oldest event when full.
  • The offset needs a monotonic clock that keeps counting in sleep. ProcessInfo.systemUptime does not count sleep.
  • Uptime and boot-time APIs are on Apple's required-reason list. So are UserDefaults and file timestamp APIs. The SDK declares each reason in its privacy manifest.

Background and flush.

  • The SDK has no SwiftUI scene. It listens for the app-did-enter-background notification and calls beginBackgroundTask for a short final flush.
  • A flush that must survive suspension is a file uploaded by a background URL session. It does not survive a force quit.
  • BGTaskScheduler only gives a later chance to run. It does not keep work alive.

Storage and identity.

  • The queue is plain SQLite or files. I avoid Core Data in an SDK, because its model and container can clash with the host's.
  • The anonymous ID is a random UUID. Keep it out of backups, and say whether it lives in the Keychain, because a Keychain item can survive a reinstall.

5. Break it, ship it, roll it back (minutes 40 to 45)

In short: Every failure keeps the data safe. Rollback is the host app's kill switch plus a new release.

FailureUser seesData holdsRecovery
Process dies mid-writeNothingEvents before the last commitNext launch reads the queue
Lost acknowledgementNothingThe fixed batchResend the same batch ID
Batch arrives out of orderNothingA counter per installThe server orders by event time, not by arrival
Wrong device clockNothingTwo timestampsThe server estimates the true time
Background kill or throttleLater deliveryThe queue on diskFlush at foreground or next launch
Low storage or evictionNothingThe newest eventsDrop the oldest, count by reason
User logs out or switches account with events queuedNothingEvents with the identity they had at trackKeep sending them under that identity. Only new events get the new one
Old app version meets new server contractNothingOld batchesThe server accepts every version

Rows not linked to a source are my design choices. Sources are in Further reading.

At release:

  • A Play staged rollout can be halted, but users who have the build keep it (Play help). A bad SDK version stays until users update.
  • Old SDK versions stay in the field. The server accepts every format version.
  • The host app's kill switch for the SDK is a remote flag that stops collection and upload. It reaches only devices that fetched it.
  • A flag cannot change the disk schema, the public API or the privacy manifest. Those need a new release.

Say this. "I start with a small share of one host app. Its crash-free rate (the share of sessions without a crash) and start time must not move. I turn off sampling and auto-capture. I cannot take a build back from users, so the kill switch comes first."

6. Follow-ups that change a constraint

In short: Each follow-up changes one constraint. These are practice prompts, not a claim about real interviews.

  1. The host calls track 10,000 times in a loop at launch. Strong: the bounded inbox drops the oldest events, a per-name limit stops the loop, and counters show it. Weak: "make the queue bigger."
  2. The host wants screens and taps recorded without code. Strong: off by default, because it adds volume and can capture text the host never meant to send. Weak: "capture everything and filter later."
  3. The host has a widget or service in another process. Strong: one lock works only inside one process. Give the store one owner process, or use short SQLite transactions. Weak: "one writer, so no problem."
  4. A user withdraws consent, or asks for erasure, with events queued and others already sent. Strong: opt-out deletes the queue, and a deletion hook asks the server to erase sent data. Weak: "stop sending."
  5. After a release, upload volume doubles and the host's crash-free rate drops. Strong: use the kill switch first, then compare delivery by SDK version. Weak: "roll back the release."
  6. The server changes the event shape while three old SDK versions are in the field. Strong: the server reads all versions, and new fields are added, not changed. Weak: "force an update."

7. What changes by level

In short: Mid builds the queue, senior makes it safe, staff adds the decision and the rollout.

These levels are my own reading of the bar, drawn from vendor and prep material (courses and books), not any company's rubric.

  • Mid-level: a small public API, a SQLite queue, batching, retry, opt-out. "I save the event first and delete it after the server says yes."
  • Senior: track never blocks, one writer, fixed batches, two timestamps, a counted drop policy, consent before disk. "A retry must send the same batch, or the server cannot tell it is a repeat."
  • Staff: build or buy, a host kill switch, version adoption, the SDK's own cost in the host. "The host's crash-free rate and start time are my guardrails, not my drop rate."

Common weak answers. Spending the time on the server. Never testing a kill between track and send. Naming a vendor SDK without saying why. Leaving consent to the end. Forgetting that an SDK crash counts against the host. These repeat across public prep material. They are not a dataset.

Staff answer: the decision and the rollout

Decision: a platform team owns the SDK and provides a host kill switch. Alternative: a vendor SDK. It starts faster but gives up control of the data format. Revisit trigger (the sign to decide again): the SDK costs more to keep than the control is worth. Then buy one and hide it behind our API.

Measure: drop counters by reason, delivery by SDK version, and the SDK's start-up cost. Guardrail (a number that must not get worse): the host's crash-free rate and start time, when a new SDK version is released.

Rollback on mobile: the kill switch reaches only devices that fetched the config. A bad build cannot be taken back. The push SDK case is similar.

What I read and what is my view: the design and the metrics are my opinion. The WorkManager timing, App Standby limits and privacy manifest rules were read on the linked pages. See also the native vs cross-platform guide.

Test yourself

In short: Seven questions from this case. Answer each one out loud first, then open the answer.

1. What does track promise?

Only that the SDK took the event. It returns nothing to wait on, and the event reaches disk within about one second. Sending each event as it happens would fail offline or when the app is killed before the answer.

2. The app is killed before the commit. What did you lose?

At most one commit group. At 5 events a second that is about 5 events, and a count rule of 20 caps a spike. The window is a number you can state.

3. Why store two times for each event?

The device clock can be wrong. Each event keeps the device time and an offset since boot, which the user cannot change. The batch adds its send time and the server adds its receive time to estimate the true time.

4. A retry must not count an event twice. How?

The first time events are picked, they get a batch ID and the SDK records which events belong to it. A retry sends the same batch, even if newer events arrived. The batch is deleted only when the server says yes, and the server skips an ID it has seen.

5. Where does the consent check go?

At track, before the event is saved. Unknown acts as denied. Opt-out stops collection, deletes the queue and cancels uploads. Filtering at upload fails when the user says no after events are on disk.

6. The app is rarely opened. How does the queue empty?

The SDK flushes when the app goes to the background and at the next launch. WorkManager is only a backup, because periodic work can be delayed and a restricted app may run jobs about once a day. No delivery time is promised.

7. Which clock do you use for the event offset on iOS, and why?

One that keeps counting in sleep. ProcessInfo.systemUptime does not count sleep, so it is the wrong choice. Uptime and boot-time APIs are also on Apple's required-reason list, so the SDK declares each reason in its privacy manifest.

Further reading (official docs)

Further reading (other, not official)

Prep material that shaped the questions I asked. These are references, not sources of wording. I read only the public parts of the commercial ones.

  • The weeeBox mobile design repository
  • The analytics SDK lesson and question list from DesignGurus
  • The ByteByteGo mobile system design material
  • The Segment, PostHog and Amplitude mobile SDK docs, read as examples of vendor defaults
  • The mobile telemetry lesson from DevPath
Words on this page (16)
Acknowledgement
A short reply that says the server got a message. If this reply is lost, the app does not know, so it sends the message again.
Actor
A Swift type that runs one task at a time. This keeps its data safe when many tasks use it.
Crash-free rate
The share of sessions that end without a crash.
Exponential backoff
Waiting longer after each failure. For example, wait 1 second, then 2, then 4.
Host app
The app that contains an SDK. You write the SDK, and another team writes the host app.
Kill switch
A remote flag that turns a feature off at once. It is the one rollback that reaches apps that are already installed.
Main thread
The thread that draws the screen. If slow work runs on it, the screen freezes.
Monotonic clock
A clock that only moves forward. The user cannot change it, so it is good for measuring how much time passed.
Privacy manifest
A file in an iOS app or SDK. It lists the data that the code collects and the system APIs that it uses.
Remote flag
A setting that the server can change. It can turn a feature on or off without a new release.
Repository
The class that reads and writes data for the rest of the app. It hides whether the data comes from the network or the database.
Rollback
Going back to the old behavior after a problem. A build on a user's phone cannot be taken back, so teams use a kill switch.
SDK
Software development kit. Code that other developers add to their own apps.
Staged rollout
A release to a growing share of users, not to everyone at once. It limits the harm of a bad release.
ViewModel
A class that holds the state of one screen. It survives a screen rotation.
WorkManager
Android's tool for background work that must run later. The work survives when the app closes or the phone restarts.

Read the whole glossary

Verification notes (last reviewed 14 Oct 2026)

What I checked on official pages (14 Oct 2026).

  • Android App Startup: content providers are expensive to start and start in no set order.
  • Android WorkManager: periodic work repeats at most every 15 minutes and can be delayed. App Standby Buckets limit jobs for rarely used apps.
  • Android: SDK authors should respect the consent the host collected.
  • Apple privacy manifests: when an SDK needs one, required-reason APIs, tracking domains.
  • Play and App Store Connect: staged and phased rollouts can be paused but not recalled.

My own design, not documented rules.

  • The promise of track, the fixed batch, the two-clock estimate, the consent gate, the numbers, the failure rows, the scripts and the level text.
  • The follow-up questions are my reconstruction from public prep material, not transcripts of real rounds.

What I did not verify.

  • Exact App Standby bucket rules for each Android version.
  • What URLSession reports for blocked tracking domains.
  • No iOS engineer has reviewed the iOS parts.

Questions or corrections?

Add them to the discussion thread for this case on GitHub. To post, you need a free GitHub account. What you write there is public and follows GitHub's terms. Good answers are added to this page.

Keep reading

Get the free one-page cheat sheet

One page: the five steps, a 45-minute time plan and two checklists. Print it or keep it on your phone.

We email you the cheat sheet after you confirm your address. You can also open it now from the Start here page. You also get a short email each week with a follow-up round, and a note when a new case is published. Unsubscribe any time. Privacy.