Design an analytics SDK for Android apps

Learn to design an analytics SDK in an Android system design interview: non-blocking init, Room batching, WorkManager flush, consent and binary size. About 42 minutes.

The question

Design an analytics SDK that an Android app integrates to collect user events, store them locally, and send them to a backend. The SDK must not block app startup, must respect user consent, and must work offline.

Clarify before you design:

  • Is the SDK a library module inside the host app's process, or does it need to work across several processes of the host app?
  • What is the expected event volume per session: hundreds or tens of thousands?
  • Does the backend need real-time delivery, or is a delay of minutes (or longer) acceptable?
  • What consent model does the host app use: opt-in before any collection, a simple on/off, or tiered levels?
  • Should the SDK support multiple backends, or is there one fixed endpoint?
  • What is the maximum acceptable binary-size increase for the host app?
  • Is it acceptable to lose a small window of in-memory events on process death, or must every event be persisted before logEvent returns?

Requirements

Functional

  • Expose a small public API: logEvent(name, properties), setConsent(level), flush(). The app calls these from any thread.
  • Store events locally in Room so they survive process death and are available when the network returns.
  • Batch stored events and POST them to the backend from a WorkManager worker, with network and battery constraints.
  • Gate every write and upload on the current consent level. On opt-out, stop collection and purge local data.
  • Do not collect PII. Drop property keys on a configurable deny-list before events reach the local store, as a safety net.
  • Support a configurable size cap on the local store; when exceeded, drop the oldest pending events.

Non-functional

  • Initialization must add as little as possible to cold start. No disk or network I/O on the main thread.
  • The SDK must work fully offline. Events queue locally and upload when connectivity returns.
  • Battery impact must be small. Uploads are batched, run with constraints, and avoid frequent wake-ups.
  • Memory stays bounded. The in-memory buffer has a fixed capacity.
  • Binary size added to the host app must be small. Avoid forcing large transitive dependencies on the host.
  • The SDK must not take over the host app's own setup, such as its WorkManager configuration.
  • The SDK must be testable in isolation without a real backend or a real WorkManager schedule.

Out of scope

  • Backend ingestion pipeline, data warehouse, or dashboard design. The client sends a batch and expects a 2xx.
  • User-identity resolution, account linking, or cross-device tracking. The SDK sends events tagged with a random install ID.
  • A full A/B testing or feature-flag system. The SDK may read a remote config for its own tuning, but it does not own that system.

High-level architecture

The SDK is a library module that runs inside the host app's process. It exposes one public interface, Analytics, with logEvent, setConsent, and flush.

API layer. A thin facade. Validates input, drops deny-listed keys, stamps a timestamp and an event ID, and hands the event to the core with a non-blocking trySend. No I/O.

Core engine. A coroutine scope owned by the SDK (SupervisorJob plus an injected IO dispatcher). It owns a bounded Channel created with BufferOverflow.DROP_OLDEST, so trySend never blocks or fails and the oldest buffered event is dropped when the buffer is full. A single consumer coroutine drains the channel and inserts events into Room in small batches, one transaction per batch. Before writing, it checks the current ConsentLevel from a StateFlow.

Local store. A Room database with one table, events. Each row is one event with its properties serialized as JSON. After each insert the DAO trims the table back under the size cap by deleting the oldest rows.

Network and scheduler. A CoroutineWorker reads a batch of pending rows, POSTs it, and deletes those rows after a 2xx. It runs as unique work with NetworkType.CONNECTED and setRequiresBatteryNotLow(true). A one-time request is enqueued when enough events are pending or when the app goes to the background; a periodic request (minimum interval 15 minutes) is a safety net. Transient failures return Result.retry() with exponential backoff.

Consent and privacy. A ConsentManager stores the level in DataStore and exposes it as a StateFlow. Until the stored value has loaded, the engine buffers events in memory and writes nothing. Opt-out stops collection, cancels the SDK's work, and purges local data.

Initialization. The SDK ships an App Startup Initializer in its own library manifest, so it merges into the host app automatically. create() runs on the main thread, so it only stores the application context, builds the SDK object and returns. Opening Room, reading DataStore, and enqueuing work happen later on a background dispatcher.

ComponentResponsibility
Analytics APIPublic interface the host app calls. Validates input, drops deny-listed keys, enqueues with trySend. No I/O.
Event CollectorConsumer coroutine on the injected IO dispatcher. Drains the Channel and inserts events into Room in batches.
Room StoreSingle-table local database. Holds pending events and trims the oldest rows when over the size cap.
Upload WorkerCoroutineWorker that reads a batch of pending rows, POSTs it, and deletes the rows after a 2xx.
ConsentManagerHolds the current ConsentLevel in a StateFlow backed by DataStore. Gates writes and triggers purge on opt-out.
SDK InitializerApp Startup Initializer declared in the SDK's manifest. Cheap create(); heavy work is deferred to a background thread.
Health ReporterCounts drops, upload failures and queue depth, and sends them as a small, rate-limited self-telemetry event.

Data model and API

import androidx.room.Dao
import androidx.room.Entity
import androidx.room.Insert
import androidx.room.PrimaryKey
import androidx.room.Query
 
enum class ConsentLevel { GRANTED, ESSENTIAL_ONLY, DENIED }
 
data class AnalyticsEvent(
    val id: String,              // random UUID, lets the backend drop duplicates
    val name: String,
    val timestamp: Long,
    val properties: Map<String, String>,
    val sessionId: String
)
 
@Entity(tableName = "events")
data class EventEntity(
    @PrimaryKey val id: String,
    val name: String,
    val timestamp: Long,
    val propertiesJson: String,
    val sessionId: String
)
 
@Dao
interface EventDao {
    @Insert
    suspend fun insertAll(events: List<EventEntity>)
 
    @Query("SELECT * FROM events ORDER BY timestamp LIMIT :limit")
    suspend fun oldest(limit: Int): List<EventEntity>
 
    @Query("DELETE FROM events WHERE id IN (:ids)")
    suspend fun deleteByIds(ids: List<String>)
 
    // Keep only the newest :maxRows rows.
    @Query("DELETE FROM events WHERE id NOT IN (SELECT id FROM events ORDER BY timestamp DESC LIMIT :maxRows)")
    suspend fun trimTo(maxRows: Int)
 
    @Query("DELETE FROM events")
    suspend fun deleteAll()
}
 
data class BatchRequest(
    val events: List<EventDto>,
    val appVersion: String,
    val installId: String        // random ID created by the SDK, reset on purge
)
 
data class EventDto(
    val id: String,
    val name: String,
    val ts: Long,
    val props: Map<String, String>
)
 
interface Analytics {
    fun logEvent(name: String, properties: Map<String, String> = emptyMap())
    fun setConsent(level: ConsentLevel)
    fun flush()
}
  • installId is a random UUID the SDK creates and stores. Do not use hardware identifiers. If the product also needs the advertising ID, read it only with the right consent. On Android 13+ the app must declare the com.google.android.gms.permission.AD_ID permission, and a user who deletes the ID gets zeros back.
  • Each ID in IN (:ids) is a bound SQL parameter, and SQLite limits how many one statement can have. Keep upload batches well below that limit, which also keeps each request small.

Deep dives

Non-blocking initialization with App Startup

Many SDKs used to initialize themselves with their own ContentProvider. The App Startup docs warn that content providers are expensive to instantiate and run in an undetermined order, so one provider per library adds up. App Startup gives every library one shared InitializationProvider. The SDK declares its Initializer as a meta-data entry under that provider in its own library manifest, and manifest merging adds it to the host app. The host needs no code in Application.onCreate.

Initializer.create() runs on the main thread before Application.onCreate, so it must stay cheap. It stores the application context, creates the SDK scope and channel, and returns. Opening Room, loading consent from DataStore, and enqueuing work run later on a background dispatcher. Events logged before that finishes wait in the bounded channel.

Give the host control. A host app can disable the SDK's automatic init by removing its meta-data entry with tools:node="remove", then call AppInitializer.getInstance(context).initializeComponent(...) later, for example after consent. Document this. The SDK can also ship a Baseline Profile for its hot-path classes, so they are compiled ahead of time when the host app installs.

Do not fight the host app's WorkManager

The SDK uses the host app's single WorkManager instance, so it must play nicely with it:

  • Never call WorkManager.initialize() from the SDK, and never remove WorkManagerInitializer from the SDK's manifest. That setup belongs to the host app.
  • Do not list WorkManagerInitializer in your Initializer.dependencies(). If the host uses on-demand initialization (its Application implements Configuration.Provider), that dependency would force WorkManager to start early with the default configuration instead of the host's.
  • Call WorkManager.getInstance(context) lazily, off the startup path. With on-demand init it picks up the host's configuration.
  • Use a plain CoroutineWorker with the standard constructor, so it works with the default worker factory and with a host's custom factory that falls back to it.
  • Prefix unique work names (for example "acme-analytics-upload") so they never collide with the host's own work names.

Batching, uploading, and retry with WorkManager

The upload worker reads the oldest pending rows, up to a configurable batch size, and serializes them into a BatchRequest. On a 2xx it deletes exactly those rows by ID and loops until the table is empty or a limit is reached. A worker run is limited (roughly 10 minutes) and can be deferred by Doze, so each run uploads a bounded amount and leaves the rest for the next run.

Error handling:

  • IOException, HTTP 5xx, or 429: return Result.retry(). The rows stay in Room and WorkManager applies exponential backoff.
  • Other 4xx such as 400: the server will never accept this batch. Log it in the health counters and delete it, so one bad batch does not block the queue forever.
  • Catch only IOException and HttpException, so CancellationException still propagates when the work is cancelled.

Delivery is at least once. If the process dies after the server accepted a batch but before the rows were deleted, the next run sends them again. That is why every event carries a random ID: the backend drops duplicates by ID. Suspend calls to Room and Retrofit are already main-safe, but the worker runs off the main thread anyway.

Scheduling:

  • When the pending count crosses a threshold, and when the app goes to the background (ProcessLifecycleOwner ON_STOP), enqueue a one-time unique request with ExistingWorkPolicy.KEEP. flush() does the same.
  • Keep a unique periodic request with ExistingPeriodicWorkPolicy.KEEP as a safety net. The minimum interval is 15 minutes.
  • A periodic and a one-time run could overlap. Guard the upload loop with a Mutex inside the SDK so only one batch is in flight at a time.

Consent is a StateFlow<ConsentLevel> backed by DataStore. The engine checks it before every write. GRANTED allows all events. ESSENTIAL_ONLY allows only an allow-list of events the host app has marked as essential, if its legal review permits that. DENIED blocks all writes and purges local data. Which level is allowed by default, and under which law, is the host app's decision; the SDK only enforces what it is told. Until the stored level has loaded, write nothing.

When consent drops to DENIED, the SDK stops the consumer, cancels its unique work with cancelUniqueWork, deletes all rows, and resets the install ID. Cancelling the work also cancels a running CoroutineWorker, which cancels its in-flight suspend HTTP call. The request may already have reached the server, so the backend also needs a deletion path keyed by install ID.

Do not rely on a deny-list alone. Matching key names like email or phone is only a safety net; the real rule is that the SDK's event schema has no fields for PII. On Google Play, the host app's developer must declare data that SDKs send off the device in the Data safety form. Publish a clear list of what the SDK collects so they can fill it in accurately.

Threading model and lifecycle safety

logEvent may be called from any thread. It calls trySend on the channel and returns at once, with no locks and no I/O. The consumer runs on an injected IO dispatcher so tests can swap it. The SDK holds only the Application context, never an Activity or Fragment. All coroutines live in the SDK's own scope with a SupervisorJob, so one failed child does not kill the collector. Do not add a close() hook tied to Application.onTerminate: that callback is never called on real devices. Instead, drain the channel to Room when the app goes to the background. In debug builds, StrictMode catches accidental main-thread disk access.

Trade-offs

DecisionOptionsWhat to pick and why
Local storageRoom (SQLite), a plain file with line-delimited JSON, or DataStore.Room. It gives transactions, easy "oldest N" reads, deletes by ID, and a size-cap query. A file log is cheap to append but hard to trim and to delete from safely. DataStore rewrites its whole file on each update, so it does not suit a growing event queue. Cost: Room adds a dependency to the host app.
Upload schedulingWorkManager, AlarmManager with a BroadcastReceiver, or an in-process timer.WorkManager. Its work survives process death and reboot, it respects network and battery constraints, and it handles backoff. Alarms are cleared on reboot, know nothing about network state, and exact alarms are restricted. An in-process timer dies with the process. Cost: delivery is deferred, and Doze can delay it further.
Write pathInsert every event into Room as it arrives, or buffer in a bounded Channel and insert in batches.Bounded Channel with batched inserts. logEvent never waits for disk either way, but batching means fewer transactions and less disk work. Cost: events still in the channel are lost if the process dies, so keep the buffer small and drain it on background.
Upload triggerFixed count, fixed time interval, or both.Both, with values the host app can configure. Count-only delays delivery for low-volume apps. Time-only can build large batches for high-volume apps. There is no universal right number.
Consent granularityBinary on/off, or tiered levels.Tiered (GRANTED, ESSENTIAL_ONLY, DENIED), with DENIED or a host-chosen level as the default. It lets the host keep the events its legal review allows without a second SDK. Cost: more states to test, and the host must decide what counts as essential.

What breaks in production

The SDK slows cold start
  • After an SDK update, the host app's startup traces show extra time before the first frame.
  • The cause: the SDK's Initializer.create() read its saved config with runBlocking on DataStore and opened the Room database on the main thread.
  • Because App Startup runs initializers before Application.onCreate, every cold start pays this cost.
The fix
  • Make create() do only cheap in-memory setup. Load DataStore and open Room on a background dispatcher, and buffer early events in the channel meanwhile.
  • Let the host disable auto-init with tools:node="remove" and start the SDK through AppInitializer when it wants.
  • Run StrictMode in the sample app's debug build, and add a cold-start Macrobenchmark to the SDK's CI that compares the sample app with and without the SDK.
Data loss when the process is killed before events reach Room
  • After a crash or a force-stop, the last moments of events are missing on the backend.
  • The cause: events were still in the in-memory Channel and had not been inserted into Room when the process died.
The fix
  • Keep the channel small and let the consumer insert small batches quickly, so few events wait in memory.
  • Drain the channel to Room when the app goes to the background (ON_STOP), the usual moment before the system kills a process.
  • Accept a small loss window as normal for analytics and document it. Work already enqueued in WorkManager is persisted, so only the in-memory buffer is at risk.
One bad batch blocks the queue forever
  • Uploads stop for a subset of users, and their local tables grow until the size cap starts dropping events.
  • The cause: one event had a malformed property, the server answered 400, and the worker returned Result.retry() for every error. The same batch was retried again and again.
The fix
  • Retry only transient errors (IOException, 5xx, 429). For other 4xx, delete the batch and count it in the health telemetry.
  • Validate event names and property sizes in the API layer, so bad events never reach the store.

Common mistakes in this round

  • Doing I/O in logEvent or in Initializer.create. Both can run on the main thread. Reading config or opening the database there adds jank or startup time on every call. Instead, trySend into a bounded channel and do all I/O on a background dispatcher.
  • Calling WorkManager.initialize from the SDK. It overrides or crashes against the host app's own configuration. Instead, call WorkManager.getInstance(context) lazily and let the host own setup.
  • Hardcoding a batch size as a universal constant. There is no standard number. Make batch size and upload thresholds configurable with sensible defaults, and tune them with real data.
  • Writing events before checking consent. Events written before the consent check end up on disk, and maybe on the server. Load consent first, check it before every write, and purge on DENIED.
  • Forcing heavy transitive dependencies. Every library the SDK depends on lands in the host app and can force a version upgrade or a conflict with the host's own copy. Keep the dependency list short, use implementation rather than api so dependencies do not leak into the host's compile classpath, avoid DI frameworks inside the SDK, and measure the size delta in a sample app built with R8.
  • Shipping without consumer R8 rules. If the SDK uses reflection (for example for JSON models), the host app's R8 can strip or rename what it needs, and the SDK breaks only in release builds. Put the keep rules in a file listed under consumerProguardFiles in the library's build.gradle.kts, so they ship inside the AAR and apply to the host build.
  • Retrying every error. A 400 will never succeed. Retry only transient failures, or one bad batch blocks the queue.
  • No testing hooks. Expose an internal EventSink or transport interface that tests replace with a fake, and test the worker with TestListenableWorkerBuilder.

Follow-up questions

Answer out loud first. Then reveal the answer and compare it at each depth.

“What happens when the app is killed mid-upload?”

“How do you handle a consent change from GRANTED to DENIED?”

“How do you test the SDK in isolation?”

“How do you keep the SDK from hurting the host app's size and startup?”

Self-review checklist

  • Public API is small: logEvent, setConsent, flush. logEvent uses trySend and does no I/O.
  • The App Startup Initializer ships in the SDK manifest, create() is cheap, and the host can disable it and call AppInitializer later.
  • The SDK never calls WorkManager.initialize() and does not depend on WorkManagerInitializer.
  • Events are stored in Room with a configurable size cap; the oldest rows are dropped on overflow.
  • Uploads use unique work with NetworkType.CONNECTED, battery-not-low, Result.retry() only for transient errors, and delete rows by ID after a 2xx.
  • Delivery is at least once; event IDs let the backend drop duplicates.
  • Consent loads before any write. DENIED cancels work, purges rows and resets the install ID. The schema has no PII fields.
  • Dependencies are few and use implementation; keep rules ship via consumerProguardFiles; size and startup are measured in CI.
  • Testing hooks exist: injected dispatcher and transport, in-memory Room, TestListenableWorkerBuilder.