# 3. Fetching Caching and Refreshing
Part of [[Remote Config and Live Tuning]]. Previous: [[2. The Tuning Schema and Layered Values]]. Next: [[4. Game Overrides Rollouts and Kill Switches]].
## 3.1 The startup timeline
The rule is **never wait on the network**. On launch:
1. `Awake`: build `TuningValues` from the schema (defaults), then apply the disk cache from the last session. The game can start right now with last session's tuning.
2. `Start`: in the background, initialize Unity Services, sign in, fetch.
3. When the fetch succeeds, apply it as the `Remote` layer and save it to the cache. Listeners get `Changed` for whatever moved.
4. If it fails or times out, log a warning and carry on with cached values. Retry later with backoff.
A player who installs the game offline gets build defaults. A returning player who's offline gets last session's tuning. Nobody gets a loading screen that waits on a server.
## 3.2 When to fetch again
Fetching once per launch is fine for PC games that people close. Mobile games sit in the background for days, so also fetch on resume and every half hour. `RefreshPolicy` decides, as pure C# so it can be tested:
**`RefreshPolicy.cs`**
```csharp
using System;
/// <summary>
/// When to fetch again: at startup, when the app returns from the background after a while, and on
/// a slow timer during long sessions. Backs off after failures so an outage doesn't hammer the service.
/// </summary>
public sealed class RefreshPolicy
{
public RefreshPolicy(double minIntervalSeconds = 300, double periodicSeconds = 1800, double maxBackoffSeconds = 900)
{
MinInterval = minIntervalSeconds;
Periodic = periodicSeconds;
MaxBackoff = maxBackoffSeconds;
}
public double MinInterval { get; }
public double Periodic { get; }
public double MaxBackoff { get; }
public double LastAttempt { get; private set; } = double.NegativeInfinity;
public int Failures { get; private set; }
public bool InFlight { get; private set; }
double RetryDelay => Failures == 0 ? 0 : Math.Min(MaxBackoff, 30 * Math.Pow(2, Failures - 1));
public enum Reason { Startup, Resume, Timer, Manual }
public bool ShouldFetch(double now, Reason reason)
{
if (InFlight) return false;
var since = now - LastAttempt;
if (Failures > 0 && since < RetryDelay) return false;
switch (reason)
{
case Reason.Startup: return double.IsNegativeInfinity(LastAttempt);
case Reason.Manual: return since >= 5;
case Reason.Resume: return since >= MinInterval;
default: return since >= (Failures > 0 ? RetryDelay : Periodic);
}
}
public void Started(double now) { InFlight = true; LastAttempt = now; }
public void Succeeded() { InFlight = false; Failures = 0; }
public void Failed() { InFlight = false; Failures++; }
}
```
- **Startup**: once.
- **Resume**: if at least `MinInterval` (5 minutes) has passed since the last attempt. Flipping between apps doesn't spam the service.
- **Timer**: every `Periodic` seconds (30 minutes).
- **Manual** (the debug panel's Refresh button): at most every 5 seconds.
- **Failures** back off 30 s, 60 s, 120 s... up to 15 minutes. While one fetch is in flight, nothing else starts.
Time comes from `Time.realtimeSinceStartupAsDouble`, which keeps counting while the game is paused (`timeScale = 0`), unlike `Time.time`.
## 3.3 RemoteTuningService.cs
**`RemoteTuningService.cs`**
```csharp
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using Unity.Services.Authentication;
using Unity.Services.Core;
using Unity.Services.RemoteConfig;
using UnityEngine;
/// <summary>
/// Fetches Remote Config and feeds it into TuningValues. The game starts on build defaults
/// immediately, applies the cached values from the last session, then the fresh fetch when (if) it
/// arrives. Nothing ever waits on the network. Fetches again on resume and on a slow timer.
/// </summary>
[DefaultExecutionOrder(-1000)] // Awake before any consumer's OnEnable in the same scene
public sealed class RemoteTuningService : MonoBehaviour
{
// Attributes Remote Config can target with Game Overrides ("appVersion >= 1.4", "level > 10").
struct UserAttributes { public int level; public bool returningPlayer; }
struct AppAttributes { public string appVersion; public string platform; }
[SerializeField] TuningSchema schema;
[SerializeField] string environmentId = ""; // empty = the project's default environment
[SerializeField] float fetchTimeoutSeconds = 6f;
public static TuningValues Values { get; private set; }
public static RemoteTuningService Instance { get; private set; }
public ConfigOrigin LastOrigin { get; private set; } = ConfigOrigin.Default;
public string LastError { get; private set; }
public string PlayerId { get; private set; } = "";
/// <summary>Set by gameplay so overrides can target progress.</summary>
public int PlayerLevel { get; set; } = 1;
readonly RefreshPolicy _policy = new RefreshPolicy();
string CachePath => Path.Combine(Application.persistentDataPath, "tuning-cache.json");
void Awake()
{
if (Instance != null) { Destroy(gameObject); return; }
Instance = this;
DontDestroyOnLoad(gameObject);
Values = schema.Build();
Values.ApplyLayer(TuningLayer.Cached, LoadCache());
}
async void Start() => await TryFetch(RefreshPolicy.Reason.Startup);
void OnApplicationPause(bool paused)
{
if (!paused) _ = TryFetch(RefreshPolicy.Reason.Resume);
}
void Update()
{
if (_policy.ShouldFetch(Time.realtimeSinceStartupAsDouble, RefreshPolicy.Reason.Timer))
_ = TryFetch(RefreshPolicy.Reason.Timer);
}
public Task RefreshNow() => TryFetch(RefreshPolicy.Reason.Manual);
async Task TryFetch(RefreshPolicy.Reason reason)
{
var now = Time.realtimeSinceStartupAsDouble;
if (!_policy.ShouldFetch(now, reason)) return;
_policy.Started(now);
try
{
if (UnityServices.State != ServicesInitializationState.Initialized)
await UnityServices.InitializeAsync();
if (!AuthenticationService.Instance.IsSignedIn)
await AuthenticationService.Instance.SignInAnonymouslyAsync();
PlayerId = AuthenticationService.Instance.PlayerId;
if (!string.IsNullOrEmpty(environmentId))
RemoteConfigService.Instance.SetEnvironmentID(environmentId);
var fetch = RemoteConfigService.Instance.FetchConfigsAsync(
new UserAttributes { level = PlayerLevel, returningPlayer = File.Exists(CachePath) },
new AppAttributes { appVersion = Application.version, platform = Application.platform.ToString() });
var finished = await Task.WhenAny(fetch, Task.Delay(TimeSpan.FromSeconds(fetchTimeoutSeconds)));
if (finished != fetch) throw new TimeoutException("Remote Config fetch timed out");
var config = await fetch;
LastOrigin = config.origin;
if (config.origin == ConfigOrigin.Remote)
{
var raw = ToRaw(config.config);
Values.ApplyLayer(TuningLayer.Remote, raw);
foreach (var r in Values.Rejected) Debug.LogWarning(
quot;[Tuning] rejected {r}");
SaveCache(Values.LayerCopy(TuningLayer.Remote));
}
LastError = null;
_policy.Succeeded();
}
catch (Exception e)
{
LastError = e.Message;
_policy.Failed();
Debug.LogWarning(quot;[Tuning] fetch failed ({reason}), keeping current values: {e.Message}");
}
}
/// <summary>JSON values to invariant strings, so "1.5" never becomes "1,5" on a German PC.</summary>
static Dictionary<string, string> ToRaw(JObject config)
{
var raw = new Dictionary<string, string>();
if (config == null) return raw;
foreach (var p in config.Properties())
raw[p.Name] = p.Value is JValue v ? Convert.ToString(v.Value, CultureInfo.InvariantCulture) : p.Value.ToString();
return raw;
}
[Serializable] sealed class Cache { public List<string> keys = new List<string>(); public List<string> values = new List<string>(); }
void SaveCache(Dictionary<string, string> layer)
{
var c = new Cache();
foreach (var kv in layer) { c.keys.Add(kv.Key); c.values.Add(kv.Value); }
try { File.WriteAllText(CachePath, JsonUtility.ToJson(c)); }
catch (IOException e) { Debug.LogWarning(quot;[Tuning] cache not saved: {e.Message}"); }
}
Dictionary<string, string> LoadCache()
{
var d = new Dictionary<string, string>();
try
{
if (!File.Exists(CachePath)) return d;
var c = JsonUtility.FromJson<Cache>(File.ReadAllText(CachePath));
for (var i = 0; i < Math.Min(c.keys.Count, c.values.Count); i++) d[c.keys[i]] = c.values[i];
}
catch (Exception e) { Debug.LogWarning(quot;[Tuning] cache unreadable, ignoring: {e.Message}"); }
return d;
}
}
```
Walkthrough:
- **`[DefaultExecutionOrder(-1000)]`** makes this `Awake` run before other scripts in the scene enable, so `RemoteTuningService.Values` exists when consumers subscribe in `OnEnable`. Put the service in your first scene; `DontDestroyOnLoad` keeps it alive after that. A second copy (from loading the first scene again) destroys itself.
- **Attributes.** `FetchConfigsAsync<T, T2>(userAttributes, appAttributes)` takes two structs. Their public fields are sent to the service, where Game Overrides can target them (part 4). Remote Config requires structs, so these are `struct`s with public fields. Keep them small and never include personal data.
- **Timeout.** `Task.WhenAny(fetch, Task.Delay(...))` gives up waiting after `fetchTimeoutSeconds`. The fetch itself isn't cancelled; if it completes later, the service updates its own `appConfig`, but this script has already moved on, and the next scheduled fetch picks the values up.
- **`config.origin`** is `Remote` for fresh values, `Cached` when the runtime fell back to its own cache, and `Default` when nothing came back. Only `Remote` is applied, because we keep our own typed cache.
- **`ToRaw`** reads `RuntimeConfig.config` (a Newtonsoft `JObject`) and turns every value into an invariant-culture string. `RuntimeConfig.GetFloat` etc. would also work but need the key and type up front and hide parse failures behind a default; going through `TuningValues` reports them in `Rejected`.
- **Cache.** The `Remote` layer is saved as parallel key and value lists with `JsonUtility` in `Application.persistentDataPath/tuning-cache.json`. `JsonUtility` can't serialize a `Dictionary`, hence the lists. A corrupt file is ignored, not fatal.
- **`async void Start`** is acceptable here because `TryFetch` catches everything. Never let an exception escape an `async void` method: Unity logs it and nothing else notices.
### Set it up
1. Create an empty GameObject named `RemoteTuning` in your first scene and add **Remote Tuning Service**.
2. Drag the `TuningSchema` asset into **Schema**.
3. For a development scene or build, paste the `development` environment ID into **Environment Id**. Leave it empty in release so players get `production`. A neat alternative: set it from code under `#if UNITY_EDITOR || DEVELOPMENT_BUILD`.
4. Press Play. The Console should show no warnings if the project is linked and the keys exist. Unplug the network and press Play again: you get a `[Tuning] fetch failed` warning, and the game runs on cached values. *(Untested: the exact exception text when offline.)*
## 3.4 Gotchas
- **Sign-in shares state with other services.** If [[Cloud Save and Unity Services]] or the multiplayer services already sign in, the `IsSignedIn` check skips a second sign-in. Make sure only one script calls `UnityServices.InitializeAsync` at a time, or that each checks the state first, as this one does.
- **`SetEnvironmentID` must come before the fetch**, and it affects every later fetch.
- **The cache lives per device**, not per player. If your game has several local profiles, include the profile name in `CachePath`.
- **WebGL**: `persistentDataPath` maps to IndexedDB and writes are asynchronous; see [[Web and WebGL Builds]]. *(Unverified for this script.)*
Next: [[4. Game Overrides Rollouts and Kill Switches]].