DEV Community

Cover image for Beyond One User, One SKU: A Kotlin Field Guide to Google Play’s New Subscription Models
Android Expert
Android Expert

Posted on Originally published at Medium

Beyond One User, One SKU: A Kotlin Field Guide to Google Play’s New Subscription Models

Seats, meters, mixed carts, and variable grace windows are arriving in Play Billing. Here is how to build an Android stack that does not corrupt entitlements when they do.

In late September 2026, the Google Play team described the next set of subscription capabilities: multi-quantity purchases, usage-based billing, mixed carts, cross-developer bundles, a dynamic grace period, retention and winback offers, plus an expanded in-app messaging API. Several of these are in testing or early access, so the exact client and server surfaces will keep moving.

That is fine. The interesting engineering question is not “which method do I call.” It is “which assumptions in my codebase will these features break?” Most subscription code written over the last several years quietly assumes four things:

  1. One purchase belongs to one person.
  2. One purchase contains one product.
  3. The grace period is a constant.
  4. The only way a subscription changes state is by the user opening my app.

Every capability above attacks at least one of those. This post walks through a backend-first design in Kotlin that survives all four, and the specific failure modes I would watch for in review.

A note on scope. The code below uses Play Billing Library APIs that exist today (BillingClient, Purchase.products, acknowledgePurchase, showInAppMessages) and plain Kotlin for everything else. For the newer features I model the invariants*, not an API shape, because the public surface is still settling. Check the* Play Billing subscription docs before you wire anything to a specific method.

Setup: dependency and version assumptions

The snippets that call acknowledgePurchase, consumePurchase, and queryPurchasesAsync as suspend functions rely on the Kotlin extensions artifact. The core billing artifact exposes only the listener-based versions of those calls, so declare the KTX dependency explicitly:

// build.gradle.kts (module)
dependencies {
    // Pulls in the core library and adds the suspend extensions.
    implementation("com.android.billingclient:billing-ktx:<version>")
}
Enter fullscreen mode Exit fullscreen mode

I assume Play Billing Library 8.0 or later, because enableAutoServiceReconnection() was introduced in 8.0.0. Check the release notes for the current version before you pin one.

The running example

To keep this concrete, imagine Marginalia, a fictional study-notes app with an AI tutor. A school district wants to buy it for a department of five teachers, the AI tutor is priced per minute of generation, and the team has struck a partnership with a flashcard app to sell a joint plan. That one product touches every feature in this post.

levers

Principle one: the backend owns entitlements

Before any feature-specific advice, fix the architecture. The client launches the purchase sheet and reports a purchase token. Your backend verifies it, stores the entitlement, and listens for real-time developer notifications so it learns about changes the app never sees: a retry succeeding overnight, a winback offer accepted from the Play Store, a refund.

architecture

The client-side contract then shrinks to something small and testable:

@Serializable
enum class AccessState {
    GRANTED, RESTRICTED, DENIED,
    UNKNOWN // default for values added by a newer backend
}

@Serializable
data class Entitlement(
    val feature: String,
    val state: AccessState = AccessState.UNKNOWN,
    val validUntilEpochSeconds: Long? = null,
)

val EntitlementJson = Json {
    ignoreUnknownKeys = true
    coerceInputValues = true // unknown enum value -> default (UNKNOWN), not a crash
}
Enter fullscreen mode Exit fullscreen mode

UNKNOWN is the unglamorous hero here. Billing models are going to grow new states, and an old app build that crashes on deserialization is an old app build that locks paying users out. Decide in advance what UNKNOWN means in your product (I recommend "treat as the last known good state for up to N hours, then restrict") and test it.

Mapping Play’s states, on the server

The server translates Play’s subscription state into your own vocabulary exactly once. Note that nothing below mentions a number of days:

enum class PlayState {
    ACTIVE, IN_GRACE_PERIOD, ON_HOLD, PAUSED, CANCELED, PENDING, EXPIRED, OTHER;

    companion object {
        // Wire names mirror the Developer API's SUBSCRIPTION_STATE_* values.
        fun fromWire(raw: String): PlayState =
            entries.firstOrNull { "SUBSCRIPTION_STATE_$it" == raw } ?: OTHER
    }
}

data class PlaySubscription(val state: PlayState, val expiry: Instant)

fun PlaySubscription.toAccess(now: Instant): AccessState = when (state) {
    PlayState.ACTIVE, PlayState.IN_GRACE_PERIOD -> AccessState.GRANTED
    // "Canceled" means auto-renew is off, not that access ended.
    PlayState.CANCELED -> if (now < expiry) AccessState.GRANTED else AccessState.DENIED
    PlayState.ON_HOLD, PlayState.PAUSED -> AccessState.RESTRICTED
    PlayState.PENDING, PlayState.EXPIRED, PlayState.OTHER -> AccessState.DENIED
}
Enter fullscreen mode Exit fullscreen mode

One subtlety worth internalizing: CANCELED is a real subscription state meaning auto-renew is off but the term has not ended. The separate canceledStateContext object only explains why it was canceled (user, system, developer, or replacement) and is present only for the canceled and expired states. Use the state to decide access and the context for analytics or win-back targeting.

An exhaustive when over an enum means the compiler flags this function the day you add a state. That is the behavior you want from billing code.

Dynamic grace period: stop encoding durations

Historically, grace was a fixed window you configured, and many apps copied that number into the client (“show the red banner for seven days”). With a dynamic grace period, Play tailors the grace duration per subscriber after a decline, and adjusts the subsequent account hold so the overall recovery window you configured is preserved.

lifecycle

Consider a failure I would expect to see in the wild. A Marginalia client computes graceEnds = purchaseTime + 7.days and shows a "fix your payment" banner until then. Under per-subscriber grace, a user may enter account hold earlier than the client believes. The app keeps showing a polite banner while the backend has already restricted them, and support tickets read "it says I have three days left but the AI tutor won't open."

The fix is boring and total: the client never derives a deadline. It renders whatever Entitlement.state and validUntilEpochSeconds say.

fun Entitlement.bannerCopy(): BannerCopy? = when (state) {
    AccessState.GRANTED -> if (validUntilEpochSeconds != null && isPaymentAtRisk) BannerCopy.FixPayment else null
    AccessState.RESTRICTED -> BannerCopy.AccessPausedFixPayment
    AccessState.DENIED, AccessState.UNKNOWN -> null // paywall handles these
}
Enter fullscreen mode Exit fullscreen mode

(isPaymentAtRisk is a server-supplied flag in this sketch. Whether you derive it from Play's grace state or from your own data, the point is that it arrives from the backend.)

In-app messaging: fix declines where the user already is

The In-App Messaging API is available now, and it is the cheapest recovery lever you can pull. It lets the app surface payment-decline and price-change messages in context. The client code is short, but the lifecycle details are where teams get hurt.

suspend fun BillingClient.showTransactionalMessages(activity: Activity): Boolean =
    suspendCancellableCoroutine { cont ->
        // Play owns the sheet and the API offers no way to dismiss it or unregister the
        // listener. The best we can do on cancellation is drop our own reference to the
        // continuation so the late callback cannot pin the coroutine (and its Activity).
        var pending: CancellableContinuation<Boolean>? = cont
        cont.invokeOnCancellation { pending = null }

        val params = InAppMessageParams.newBuilder()
            .addInAppMessageCategoryToShow(InAppMessageParams.InAppMessageCategoryId.TRANSACTIONAL)
            .build()
        showInAppMessages(activity, params) { result ->
            val changed = result.responseCode ==
                InAppMessageResult.InAppMessageResponseCode.SUBSCRIPTION_STATUS_UPDATED
            pending?.takeIf { it.isActive }?.resume(changed)
            pending = null
        }
    }
Enter fullscreen mode Exit fullscreen mode

Call it once per foreground. Refresh from your backend before showing the message, and again if the message reports a status change. The ordering matters because repeatOnLifecycle cancels its block when the lifecycle drops below STARTED. If the Play sheet pushes your activity there, the second refresh is skipped for that cycle, and the first one (plus the next STARTED) has to cover you:

class MainActivity : ComponentActivity() {
    private val billing: PlayBilling by inject()
    private val entitlements: EntitlementRepository by inject()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                entitlements.refresh(force = false) // always refresh on foreground
                val updated = billing.showTransactionalMessages(this@MainActivity)
                if (updated) entitlements.refresh(force = true)
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Note that the activity calls billing.showTransactionalMessages(...), a method on the PlayBilling wrapper shown later in this post, rather than the raw extension on BillingClient. On a cold launch the activity can reach STARTED before anything has connected the client, and calling showInAppMessages on a client that is not ready fails immediately. The wrapper connects first.

Two failure modes live here. The first is calling it from a repeating timer or a recomposing UI, which spams users with the same sheet. repeatOnLifecycle bounds it to one attempt per STARTED transition, and cancels in-flight work when the lifecycle leaves that state, which is why the cancellation handling above matters. The second is trusting the callback as the source of truth. If the user fixed their card, the backend will find out through Play, not through your listener, so the refresh must happen regardless.

Multi-quantity purchases: one token, many seats

Selling to a team changes the cardinality of your data model. A single purchase can now back several seats, and the person who paid is rarely the person who uses the product.

seats

The tempting schema is users.purchase_token. It dies the first time two teachers share a purchase. The durable schema separates the purchase from the seats, and pre-creates one row per unit of quantity so that claiming a seat is a single atomic statement rather than a count-then-insert race:

class SeatRepository(private val db: Database) {

    /** Creates quantity-many empty seats the first time we see a token. Safe to call repeatedly. */
    suspend fun ensureSeats(tokenHash: String, quantity: Int) = db.tx {
        for (n in 1..quantity) {
            execute(
                """
                INSERT INTO seat (token_hash, seat_no) VALUES (?, ?)
                ON CONFLICT (token_hash, seat_no) DO NOTHING
                """.trimIndent(),
                tokenHash, n,
            )
        }
    }

    /** Claims the lowest free seat, or returns null if the purchase is full. */
    suspend fun claim(tokenHash: String, userId: UserId): Int? = db.tx {
        queryOne<Int>(
            """
            UPDATE seat SET user_id = ?
            WHERE (token_hash, seat_no) = (
                SELECT token_hash, seat_no FROM seat
                WHERE token_hash = ? AND user_id IS NULL
                ORDER BY seat_no
                LIMIT 1
                FOR UPDATE SKIP LOCKED
            )
            RETURNING seat_no
            """.trimIndent(),
            userId.value, tokenHash,
        )
    }
}
Enter fullscreen mode Exit fullscreen mode

FOR UPDATE SKIP LOCKED is what makes two simultaneous invites land on two different seats instead of one winning by accident. (db.tx, execute, and queryOne are stand-ins for whatever data layer you use.)

The failure I would plan for first is revocation fan-out. When the token’s state changes, such as a hold, a cancellation, or a refund, your entitlement job must reach every seat, not only the buyer’s account. Add a test that creates a five-seat purchase, assigns three, pushes a hold event, and asserts that all three holders flip to RESTRICTED.

Mixed carts: stop assuming one product per purchase

Mixed carts let a subscription and one-time products move through a single checkout. In Marginalia’s case, a teacher buys the monthly plan plus a starter bundle of AI minutes in one sheet.

On the client, the habit to break is reading the first element of a list. Purchase.products has always been a list; code that does purchase.products.first() was merely lucky.

class BillingUnavailableException(message: String) : IOException(message)

sealed interface Settlement {
    data object Acknowledge : Settlement   // subscriptions, non-consumables
    data object Consume : Settlement       // consumable one-time products
    data object RetryLater : Settlement
    data class Reject(val reason: String) : Settlement
}

class PlayBilling(
    context: Context,
    private val scope: CoroutineScope,
    private val backend: EntitlementApi,
) : PurchasesUpdatedListener {

    val client: BillingClient = BillingClient.newBuilder(context)
        .setListener(this)
        .enablePendingPurchases(
            PendingPurchasesParams.newBuilder().enableOneTimeProducts().build()
        )
        .enableAutoServiceReconnection()
        .build()

    private val connectLock = Mutex()

    /** Connects once; later calls return immediately while the connection is alive. */
    internal suspend fun ensureReady() {
        connectLock.withLock {
            if (client.isReady) return@withLock
            suspendCancellableCoroutine<Unit> { cont ->
                client.startConnection(object : BillingClientStateListener {
                    override fun onBillingSetupFinished(result: BillingResult) {
                        if (!cont.isActive) return
                        if (result.responseCode == BillingClient.BillingResponseCode.OK) cont.resume(Unit)
                        else cont.resumeWithException(BillingUnavailableException(result.debugMessage))
                    }
                    // With auto reconnection enabled (PBL 8+), the library retries for us.
                    override fun onBillingServiceDisconnected() = Unit
                })
            }
        }
    }

    /** Connects if needed, then shows Play's transactional messages. Returns true if status changed. */
    suspend fun showTransactionalMessages(activity: Activity): Boolean {
        try {
            ensureReady()
        } catch (e: BillingUnavailableException) {
            return false // no billing right now; the foreground refresh still runs
        }
        return client.showTransactionalMessages(activity) // extension from the in-app messaging section
    }

    override fun onPurchasesUpdated(result: BillingResult, purchases: List<Purchase>?) {
        if (result.responseCode != BillingClient.BillingResponseCode.OK || purchases == null) return
        scope.launch { purchases.forEach { settle(it) } }
    }

    internal suspend fun settle(purchase: Purchase) {
        if (purchase.purchaseState != Purchase.PurchaseState.PURCHASED) return // PENDING: wait
        ensureReady() // acknowledge/consume fail with SERVICE_DISCONNECTED on a dead connection

        // The backend validates the token, grants EVERY line item idempotently,
        // and tells us how to close the loop for this purchase.
        val settlement = runCatching {
            backend.redeem(
                token = purchase.purchaseToken,
                productIds = purchase.products,
                orderId = purchase.orderId,
            )
        }.getOrElse { Settlement.RetryLater }

        when (settlement) {
            Settlement.Acknowledge -> if (!purchase.isAcknowledged) {
                client.acknowledgePurchase(
                    AcknowledgePurchaseParams.newBuilder()
                        .setPurchaseToken(purchase.purchaseToken).build()
                )
            }
            Settlement.Consume -> client.consumePurchase(
                ConsumeParams.newBuilder().setPurchaseToken(purchase.purchaseToken).build()
            )
            Settlement.RetryLater -> Unit // picked up again by queryPurchasesAsync on next start
            is Settlement.Reject -> Unit  // log and alert; do not acknowledge
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

The ordering is the lesson. Persist the grant on your backend, then acknowledge. Acknowledge first and crash, and you have a paying user with no entitlement and a purchase Play now considers settled. Never acknowledge at all, and Play will eventually refund the purchase, which is a pleasant surprise for you and an unpleasant one for the user who has been using the product.

Because the app can be killed between the purchase and settle, also reconcile on startup. Note the first line: a BillingClient is not usable until startConnection has completed, and enableAutoServiceReconnection() only handles *re*connection after that first successful connect:

suspend fun PlayBilling.reconcile() {
    ensureReady() // startConnection must have completed before any query
    val subs = client.queryPurchasesAsync(
        QueryPurchasesParams.newBuilder().setProductType(BillingClient.ProductType.SUBS).build()
    )
    val inApp = client.queryPurchasesAsync(
        QueryPurchasesParams.newBuilder().setProductType(BillingClient.ProductType.INAPP).build()
    )
    (subs.purchasesList + inApp.purchasesList).forEach { settle(it) }
}
Enter fullscreen mode Exit fullscreen mode

With mixed carts, the redeem endpoint must be idempotent per line item, not per request. If the subscription grants fine but the credit-pack grant times out, a retry must not grant the subscription twice or skip the credits.

Cross-developer bundles: entitlements are sets, not SKUs

A bundle sold across catalogs means a single purchase can imply access in more than one product. The brittle pattern is a when (productId) that returns a feature flag. Replace it with a mapping from product to a set of entitlements, owned by the backend and versioned independently of app releases:

@JvmInline value class ProductId(val value: String)
@JvmInline value class Feature(val value: String)

class CatalogGrants(private val grants: Map<ProductId, Set<Feature>>) {
    fun featuresFor(products: Collection<ProductId>): Set<Feature> =
        products.flatMapTo(mutableSetOf()) { grants[it].orEmpty() }
}
Enter fullscreen mode Exit fullscreen mode

If Marginalia’s joint plan includes the partner’s premium flashcards, the backend map says marginalia_plus_cards -> {tutor, notes, partner_cards}. The failure mode is unglamorous: the day the partnership ends or the bundle is repriced, a hard-coded client map is stuck in every installed version. Treat unknown products as "grant nothing, log loudly," never as "grant everything."

Usage-based billing: a ledger, not a counter

For the AI tutor, prepaid metering with automatic top-ups fits the cost shape: users buy credit, spend it as they generate, and the balance refills when it drops below a threshold. The trap is implementing the balance as a mutable number.


ledger

Model it as an append-only ledger where every entry carries a unique key. Retries become harmless replays:

@JvmInline value class Credits(val units: Long) : Comparable<Credits> {
    operator fun plus(o: Credits) = Credits(units + o.units)
    operator fun minus(o: Credits) = Credits(units - o.units)
    override fun compareTo(other: Credits) = units.compareTo(other.units)
}

sealed interface DebitResult {
    data class Applied(val balance: Credits) : DebitResult
    data class Replayed(val balance: Credits) : DebitResult   // same key seen before
    data class Insufficient(val balance: Credits) : DebitResult
}

class UsageLedger(private val store: LedgerStore, private val topUpThreshold: Credits) {

    suspend fun debit(account: AccountId, key: String, cost: Credits): DebitResult =
        store.withAccountLock(account) {
            findEntry(account, key)?.let { return@withAccountLock DebitResult.Replayed(it.balanceAfter) }

            val balance = currentBalance(account)
            if (balance < cost) return@withAccountLock DebitResult.Insufficient(balance)

            val after = balance - cost
            append(account, key, delta = Credits(-cost.units), balanceAfter = after)
            if (after < topUpThreshold) requestTopUpOnce(account)
            DebitResult.Applied(after)
        }

    suspend fun credit(account: AccountId, eventId: String, amount: Credits) =
        store.withAccountLock(account) {
            if (findEntry(account, eventId) != null) return@withAccountLock
            append(account, eventId, delta = amount, balanceAfter = currentBalance(account) + amount)
            clearTopUpInFlight(account)
        }
}
Enter fullscreen mode Exit fullscreen mode

A few details that matter more than they look:

  • The key must be created by the caller before the first attempt, typically a UUID generated when the user taps “generate” and reused across retries. A key generated inside the retry loop defeats the whole mechanism.
  • Debit after the work succeeds, not before, or users pay for crashes. If the work is long and expensive, reserve first, then settle, and make both steps keyed.
  • requestTopUpOnce must be single-flight. Without an in-flight marker, a burst of requests under the threshold triggers a burst of top-up attempts.
  • A declined top-up is a first-class state. Return Insufficient and surface it in the UI. The alternative is a balance that quietly goes negative.

On the Android side, generate the key up front and let it survive process death:

class GenerateViewModel(
    private val api: TutorApi,
    private val saved: SavedStateHandle,
) : ViewModel() {

    fun generate(prompt: String) = viewModelScope.launch {
        // Created once per user intent, restored if the process is killed mid-request.
        val key = saved.getOrPut("pending_key") { UUID.randomUUID().toString() }
        val result = api.generate(prompt, idempotencyKey = key)
        saved.remove<String>("pending_key") // only after the server has answered
        render(result)
    }
}
Enter fullscreen mode Exit fullscreen mode

SavedStateHandle has no built-in getOrPut, so define the small extension yourself:

inline fun <reified T> SavedStateHandle.getOrPut(key: String, create: () -> T): T =
    get<T>(key) ?: create().also { set(key, it) }
Enter fullscreen mode Exit fullscreen mode

Retention offers, plan change, and winback: state changes the app never sees

These three features share an uncomfortable property for a client developer: they act outside your app. A retention offer appears in the Play cancellation flow. A winback offer reaches a lapsed user on the Play Store, possibly after they uninstalled. A plan change keeps a user who would have left.

So the user’s entitlement can change while your process is not running, and the first signal you get is a notification on your backend. This is the fourth assumption in the opening list, and the one most likely to be silently wrong. Two rules follow:

  1. Consume real-time developer notifications, then re-fetch the subscription state from the Developer API rather than trusting the notification body alone. Notifications are delivered at least once and can arrive out of order, so make the handler idempotent and ordered by the fetched state, not by arrival time.
  2. Refresh entitlements on every foreground, as in the activity above. A user who returned through a winback offer should see their access restored the moment they open the app, not after the next cache expiry.

Finally, none of the background optimizations Play runs for you (smart retries, backup payment methods, reminders during grace and hold, promotion-abuse checks) require code. But they do produce state transitions you did not initiate, which is one more reason the backend, not the client, has to be the source of truth.

The review checklist

If you only keep one artifact from this post, make it this one. Each row is a bug I would expect to find in a billing code review.

failure-modes

Rollout notes

  • Start with the cheapest lever. In-app messaging is available today and touches little code. Ship it, and the refresh-on-foreground habit it requires, first.
  • Land the schema changes before the features. Moving from user.purchase_token to purchase-plus-seats and from SKU flags to entitlement sets is a migration. Do it while nothing depends on it.
  • Test the unglamorous paths. Kill the process between purchase and acknowledgement. Deliver the same notification twice. Replay a debit with the same key. Send an unknown state to an old build. Each of these takes minutes to write and prevents the incidents that cost real money.
  • Watch eligibility. Several of the new capabilities are in testing with select partners. If you work with a Play partner manager, that is the route to express interest.

🔚 Closing thought

The new Play subscription models widen what you can sell: teams, metered usage, bundles, one-checkout upsells. They also retire the comfortable simplifications that made billing code short. The teams that adopt them smoothly will not be the ones with the cleverest client, but the ones whose backend already treats a subscription as a changing fact about the world rather than a flag they set once.

Source and further reading

Marginalia is a fictional app invented for this article. All code is illustrative; adapt error handling, persistence, and security review to your own stack.

🔐 Go Beyond Using Android — Master How It’s Actually Secured

If you’re building, testing, or breaking Android apps, understanding the security model beneath the SDK separates developers who follow best practices from those who truly understand why those practices exist. I highly recommend “Mastering Android Security: From Fundamentals to Advanced Practice.” It’s a comprehensive, architecture-first journey through app sandboxing, cryptography, network defense, reverse engineering, and exploitation — spanning everything from AndroidManifest.xml internals to TrustZone and the Verified Boot chain, with hands-on labs at every step.


Originally published on Medium.

Top comments (0)