Implementing Cache Migration on Mobile App Update
After app update, cache may become invalid. This isn't always obvious: old images loaded under old keys, JSON responses from API serialized in old format, HTTP cache contains headers with outdated URLs. If cache isn't invalidated on update — user sees old data mixed with new, or app crashes on deserialization.
Cache Invalidation by App Version
Simplest and most reliable approach: tie cache keys to app version or API version.
// Android — cache namespace by version
object CacheKeyBuilder {
private val appVersion = BuildConfig.VERSION_CODE
fun forImage(imageId: String) = "img_v${appVersion}_$imageId"
fun forApiResponse(endpoint: String) = "api_v${appVersion}_$endpoint"
}
On update VERSION_CODE, all keys change — old cache stops being used. But old files remain on disk and need explicit cleanup.
Cleanup Outdated Cache on Startup
// iOS
class CacheManager {
private let defaults = UserDefaults.standard
private let lastVersionKey = "lastCachedVersion"
func cleanupIfNeeded() {
let current = Bundle.main.buildVersionNumber
let last = defaults.string(forKey: lastVersionKey) ?? ""
guard current != last else { return }
clearDiskCache()
clearURLCache()
defaults.set(current, forKey: lastVersionKey)
}
private func clearDiskCache() {
let cacheDir = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!
try? FileManager.default.removeItem(at: cacheDir.appendingPathComponent("ImageCache"))
}
private func clearURLCache() {
URLCache.shared.removeAllCachedResponses()
}
}
Called in application(_:didFinishLaunchingWithOptions:) before UI initialization.
Kingfisher (iOS) and Glide (Android)
Both libraries use own disk caches. Kingfisher stores cache in Library/Caches/com.onevcat.Kingfisher.ImageCache. Cleanup:
KingfisherManager.shared.cache.clearDiskCache()
KingfisherManager.shared.cache.clearMemoryCache()
Glide: Glide.get(context).clearDiskCache() — only from background thread.
Work Scope
- Cache key versioning
- Invalidate outdated cache on first launch of new version
- Clear HTTP cache and image cache
- Background cleanup without blocking startup
Timeline
Basic cache invalidation on update: 0.5 day. With versioned keys, selective cache preservation, and background cleanup: 1 day.







