From 4544ca005fba1e2a8de0d669812e905ab196e540 Mon Sep 17 00:00:00 2001 From: IanMeyer Date: Fri, 13 Nov 2026 09:03:28 -0800 Subject: [PATCH] perf: increase remote config throttle to 15 minutes Honor the cooldown for startup subscriptions and refreshes using persisted config and in-memory fetch results. Use absolute timestamp age for clock rollback safety and inject Time for deterministic tests. --- .../com/amplitude/core/remoteconfig/README.md | 20 +- .../core/remoteconfig/RemoteConfigClient.kt | 60 +++-- .../java/com/amplitude/core/utilities/Time.kt | 5 + .../remoteconfig/RemoteConfigClientTest.kt | 94 +++++-- .../remoteconfig/RemoteConfigCooldownTest.kt | 255 ++++++++++++++++++ 5 files changed, 381 insertions(+), 53 deletions(-) create mode 100644 analytics-core/src/main/java/com/amplitude/core/utilities/Time.kt create mode 100644 analytics-core/src/test/kotlin/com/amplitude/core/remoteconfig/RemoteConfigCooldownTest.kt diff --git a/analytics-core/src/main/java/com/amplitude/core/remoteconfig/README.md b/analytics-core/src/main/java/com/amplitude/core/remoteconfig/README.md index 102eaa3b..74289736 100644 --- a/analytics-core/src/main/java/com/amplitude/core/remoteconfig/README.md +++ b/analytics-core/src/main/java/com/amplitude/core/remoteconfig/README.md @@ -34,15 +34,21 @@ iOS (`AmplitudeCore-Swift`) and Web clients so behavior is consistent across SDK signal — so callers can reliably gate setup on it. The mode controls only this *initial* delivery; afterward every subscriber receives subsequent successful fetches as updates. -- **`All`**: delivers cache immediately (if present), then the remote result, then - every subsequent successful fetch. -- **`WaitForRemote(timeout)`**: blocks the *initial* delivery on the remote up to - `timeout`; on failure/timeout falls back to cache, else a failure signal. After +- **`All`**: delivers cache immediately (if present). When that cache is stale or + absent, it also fetches remotely. It receives every subsequent successful fetch. +- **`WaitForRemote(timeout)`**: reuses fresh cached config immediately; otherwise + blocks the *initial* delivery on the remote up to `timeout`. On failure/timeout + it falls back to cache, else a failure signal. After that initial callback it receives subsequent fetches as updates, the same as `All`. - **Any successful fetch** — whether triggered by a `subscribe` or by `updateConfigs()` — delivers the latest config to **all** current subscribers (de-duplicated per subscriber by `fetchId`). Failures are never fanned out, so - subscribers keep their last valid config. `updateConfigs()` is rate-limited (5 min). + subscribers keep their last valid config. Subscriptions and `updateConfigs()` + honor a 15-minute cooldown after a successful fetch. New clients reuse valid, + fresh persisted config, including after a process restart, and report `CACHE` + with the original fetch timestamp. Reusing config does not extend the cooldown. + An in-memory success also enforces the cooldown when persistence fails. + Failed fetches do not start a new cooldown. ## Internals @@ -61,7 +67,7 @@ flowchart TD SRC{"config source?"} SRC -->|"fetch in flight"| JOIN["join the shared fetch"] - SRC -->|"recent success"| REUSE["reuse last result
(no network call)"] + SRC -->|"recent success or fresh saved config"| REUSE["reuse config
(no network call)"] SRC -->|"otherwise"| FETCH["GET /config?config_group=android
then store blob + timestamp"] JOIN --> OUT["FetchOutcome
Success(blob, ts, fetchId) · Failure"] @@ -87,6 +93,7 @@ sequenceDiagram alt blob is cached RC-->>C: onUpdate(config-or-null, CACHE, ts) end + opt cache is stale or absent RC->>N: GET /config?config_group=android alt success N-->>RC: nested blob @@ -95,6 +102,7 @@ sequenceDiagram else failure (and nothing delivered yet) RC-->>C: onUpdate(null, REMOTE, null) end + end ``` ## Compatibility diff --git a/analytics-core/src/main/java/com/amplitude/core/remoteconfig/RemoteConfigClient.kt b/analytics-core/src/main/java/com/amplitude/core/remoteconfig/RemoteConfigClient.kt index 4ca96fab..016efdff 100644 --- a/analytics-core/src/main/java/com/amplitude/core/remoteconfig/RemoteConfigClient.kt +++ b/analytics-core/src/main/java/com/amplitude/core/remoteconfig/RemoteConfigClient.kt @@ -11,6 +11,7 @@ import com.amplitude.core.Storage import com.amplitude.core.remoteconfig.RemoteConfigClient.Key import com.amplitude.core.remoteconfig.RemoteConfigClient.Source.CACHE import com.amplitude.core.remoteconfig.RemoteConfigClient.Source.REMOTE +import com.amplitude.core.utilities.Time import com.amplitude.core.utilities.http.HttpClient import com.amplitude.core.utilities.runCatchingCancellable import com.amplitude.core.utilities.toJSONObject @@ -28,6 +29,7 @@ import java.lang.ref.WeakReference import java.net.URLEncoder import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicLong +import kotlin.math.abs import kotlin.math.pow import kotlin.random.Random @@ -57,12 +59,13 @@ public interface RemoteConfigClient { */ @RestrictedAmplitudeFeature public sealed class DeliveryMode { - /** Deliver cached config immediately (if present), then remote, and every subsequent successful fetch. */ + /** Deliver cache immediately (if present), refresh it when stale, and receive every subsequent successful fetch. */ public data object All : DeliveryMode() /** - * Block the initial delivery on the remote up to [timeoutMs] — then fall back to - * cache, else a failure signal. Subsequent successful fetches are delivered as + * Reuse fresh cached config immediately; otherwise block the initial delivery + * on the remote up to [timeoutMs], then fall back to cache, else a failure signal. + * Subsequent successful fetches are delivered as * updates, the same as [All]. */ public class WaitForRemote(public val timeoutMs: Long) : DeliveryMode() { @@ -144,6 +147,7 @@ internal class RemoteConfigClientImpl( private val httpClient: HttpClient, private val logger: Logger, private val maxRetryDelayMillis: Long = DEFAULT_MAX_RETRY_DELAY_MS, + private val time: Time = Time(), ) : RemoteConfigClient { /** Wraps the analytics event [storage], keeping the existing on-disk keys. */ constructor( @@ -178,7 +182,7 @@ internal class RemoteConfigClientImpl( private const val US_REMOTE_CONFIG_URL = "https://sr-client-cfg.amplitude.com" private const val EU_REMOTE_CONFIG_URL = "https://sr-client-cfg.eu.amplitude.com" private const val CONFIG_GROUP = "android" - private const val MIN_FETCH_INTERVAL_MS: Long = 5 * 60 * 1_000L + private const val MIN_FETCH_INTERVAL_MS: Long = 15 * 60 * 1_000L private const val DEFAULT_MAX_RETRY_DELAY_MS: Long = 8_000L private const val HTTP_TOO_MANY_REQUESTS = 429 @@ -317,9 +321,9 @@ internal class RemoteConfigClientImpl( } /** - * Deliver cached config immediately if present, then the remote result when it - * arrives. A failure (null config, null timestamp) is delivered only when nothing - * else was — no cache and the fetch failed — guaranteeing exactly one initial + * Deliver cached config immediately if present. Fetch remotely when the cache + * is stale or absent. A failure (null config, null timestamp) is delivered only + * when nothing else was — no cache and the fetch failed — guaranteeing exactly one initial * callback. Mirrors iOS `.all`. */ private fun subscribeAll( @@ -340,7 +344,9 @@ internal class RemoteConfigClientImpl( // Deliver to this subscriber from its own awaited outcome — never relying on // a broadcast snapshot. deliverRemote de-dups by fetchId, so a concurrent // refresh broadcast of the same fetch won't double-deliver. - when (val handle = obtainSubscribeFetch()) { + when (val handle = obtainSubscribeFetch(cached)) { + is FetchHandle.Cached -> + weakCallback.deliverFirst(handle.data.config, CACHE, handle.data.timestamp) is FetchHandle.Reuse -> weakCallback.deliverRemote( resolveDotPath(handle.success.blob, key.value), @@ -363,8 +369,8 @@ internal class RemoteConfigClientImpl( } /** - * Block the initial delivery on the remote fetch up to [timeoutMs]. On success - * deliver remote; on failure or timeout fall back to cache, or a failure signal + * Reuse fresh cached config immediately; otherwise wait for the remote fetch up to [timeoutMs]. + * On success deliver remote; on failure or timeout fall back to cache, or a failure signal * (null config, null timestamp) when no cache exists. Exactly one *initial* callback * is delivered; subsequent successful fetches are delivered as updates (via the * broadcast in [startFetchLocked]), the same as [RemoteConfigClient.DeliveryMode.All]. @@ -378,7 +384,10 @@ internal class RemoteConfigClientImpl( registerSubscriber(key, weakCallback) coroutineScope.launch { - when (val handle = obtainSubscribeFetch()) { + val stored = getStoredConfigData(key.value) + when (val handle = obtainSubscribeFetch(stored)) { + is FetchHandle.Cached -> + weakCallback.deliverFirst(handle.data.config, CACHE, handle.data.timestamp) is FetchHandle.Reuse -> // deliverRemote (not a fallback): sets lastFetchId so the fetch's own // broadcast de-dups, and leaves the subscriber open to later updates. @@ -444,10 +453,12 @@ internal class RemoteConfigClientImpl( override fun updateConfigs() { coroutineScope.launch(networkIODispatcher) { if (shouldRateLimit()) { - logger.debug("RemoteConfig update skipped: within 5-minute window") + logger.debug("RemoteConfig update skipped: within 15-minute window") return@launch } - startOrJoinFetch() + if (startOrJoinFetch() == null) { + logger.debug("RemoteConfig update skipped: within 15-minute window") + } } } @@ -474,8 +485,10 @@ internal class RemoteConfigClientImpl( } } - /** How a subscribe obtains its config: a reusable recent success, or a live fetch. */ + /** A subscription reuses a fresh saved config or in-memory success, or joins a live fetch. */ private sealed interface FetchHandle { + data class Cached(val data: ConfigData) : FetchHandle + data class Reuse(val success: FetchOutcome.Success) : FetchHandle data class Pending(val deferred: Deferred) : FetchHandle @@ -483,21 +496,24 @@ internal class RemoteConfigClientImpl( /** * Obtains config for an initial subscribe: joins an in-flight fetch, reuses a - * recent successful result to avoid hammering the server, or starts a new fetch. - * Never rate-limited — a subscribe must always resolve to a delivery. + * recent successful result or fresh saved config, or starts a new fetch. + * A fresh saved config honors the cooldown across client and process restarts. */ - private fun obtainSubscribeFetch(): FetchHandle { + private fun obtainSubscribeFetch(cached: ConfigData?): FetchHandle { synchronized(fetchLock) { inFlightFetch?.let { if (it.isActive) return FetchHandle.Pending(it) } lastSuccess?.let { if (isFresh(it.timestamp)) return FetchHandle.Reuse(it) } + cached?.let { if (isFresh(it.timestamp)) return FetchHandle.Cached(it) } return FetchHandle.Pending(startFetchLocked()) } } - /** Joins an in-flight fetch or starts a new one. Used by the refresh path. */ - private fun startOrJoinFetch(): Deferred { + /** Joins a fetch or starts a refresh unless a successful fetch is still fresh. */ + private fun startOrJoinFetch(): Deferred? { synchronized(fetchLock) { inFlightFetch?.let { if (it.isActive) return it } + // A fetch may have succeeded after the storage check, even if its cache write failed. + lastSuccess?.let { if (isFresh(it.timestamp)) return null } return startFetchLocked() } } @@ -566,7 +582,7 @@ internal class RemoteConfigClientImpl( logger.error("Error fetching remote configs: ${e.message}") return FetchOutcome.Failure } ?: return FetchOutcome.Failure - val timestamp = System.currentTimeMillis() + val timestamp = time.nowMillis() val cached = CachedRemoteConfig(blob.mapValues { it.value.withJsonNulls() }.toJSONObject().toString(), timestamp) fetchedCache = cached // Persisting the blob is best-effort: a storage write failure must not discard @@ -583,14 +599,14 @@ internal class RemoteConfigClientImpl( } private fun isFresh(timestamp: Long): Boolean { - return timestamp > 0L && (System.currentTimeMillis() - timestamp) < MIN_FETCH_INTERVAL_MS + return timestamp > 0L && abs(time.nowMillis() - timestamp) < MIN_FETCH_INTERVAL_MS } private suspend fun shouldRateLimit(): Boolean { return runCatchingCancellable { val lastTs = withContext(storageIODispatcher) { remoteConfigStorage.read()?.timestamp } ?: 0L if (lastTs <= 0L) return@runCatchingCancellable false - (System.currentTimeMillis() - lastTs) < MIN_FETCH_INTERVAL_MS + isFresh(lastTs) }.getOrElse { e -> // Don't let a storage read failure leak out of the refresh coroutine or // wedge the rate limiter — fall through and let the fetch proceed. diff --git a/analytics-core/src/main/java/com/amplitude/core/utilities/Time.kt b/analytics-core/src/main/java/com/amplitude/core/utilities/Time.kt new file mode 100644 index 00000000..e49fcc1e --- /dev/null +++ b/analytics-core/src/main/java/com/amplitude/core/utilities/Time.kt @@ -0,0 +1,5 @@ +package com.amplitude.core.utilities + +internal class Time { + fun nowMillis(): Long = System.currentTimeMillis() +} diff --git a/analytics-core/src/test/kotlin/com/amplitude/core/remoteconfig/RemoteConfigClientTest.kt b/analytics-core/src/test/kotlin/com/amplitude/core/remoteconfig/RemoteConfigClientTest.kt index 9e7735e8..18751e6a 100644 --- a/analytics-core/src/test/kotlin/com/amplitude/core/remoteconfig/RemoteConfigClientTest.kt +++ b/analytics-core/src/test/kotlin/com/amplitude/core/remoteconfig/RemoteConfigClientTest.kt @@ -16,6 +16,7 @@ import com.amplitude.core.remoteconfig.RemoteConfigClient.Key.SessionReplayPriva import com.amplitude.core.remoteconfig.RemoteConfigClient.Key.SessionReplaySamplingConfig import com.amplitude.core.remoteconfig.RemoteConfigClient.Source import com.amplitude.core.utilities.InMemoryStorage +import com.amplitude.core.utilities.Time import com.amplitude.core.utilities.http.HttpClient import com.amplitude.core.utilities.http.ResponseHandler import io.mockk.coEvery @@ -37,6 +38,7 @@ import org.junit.jupiter.api.Assertions.assertFalse import org.junit.jupiter.api.Assertions.assertNotNull import org.junit.jupiter.api.Assertions.assertNull import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Nested import org.junit.jupiter.api.Test import org.junit.jupiter.api.io.TempDir import org.junit.jupiter.params.ParameterizedTest @@ -53,6 +55,8 @@ class RemoteConfigClientTest { mockk(relaxed = true) private val testDispatcher = StandardTestDispatcher() private val testScope = TestScope(testDispatcher) + private var now = System.currentTimeMillis() + private val time = mockk