MODULE 06 · SDK & LIBRARY ARCHITECTURE

Design a Pagination & Image SDK

Architect a reusable, zero-leak mobile SDK featuring single-flight request coalescing, cooperative lifecycle cancellation, OOM-safe 2-pass bitmap subsampling, and pluggable cursor pagination.

Single-Flight Coalescing Cooperative Cancellation 2-Pass Subsampling Pluggable Contracts
Act I · Scope, Requirements & SDK Budgets

SDK Guarantees & Resource Envelope

Step 1 of 5
Functional & Non-Functional Requirements
Library Contract
  • Pluggable Transport & Cache SPI: Expose minimal interfaces for NetworkTransport, MemoryCache, DiskCache, and Decoder so host apps inject their own stacks.
  • Single-Flight Request Deduplication: Coalesce concurrent requests for the same normalized key into one upstream network fetch and fan out results to all waiters.
  • Lifecycle-Bound Cancellation & Generation-Tag Guard: Abort orphaned jobs when the last waiter detaches and reject stale recycled-cell paints via monotonic view generation tags.
  • Header-Only Bounds Decode & Subsampling: Read image dimensions without allocating pixel memory, compute power-of-2 sampleSize, and decode into pooled buffers.
  • Cursor Pagination with Stale-While-Revalidate: Serve cached pages at 0ms while validating ETag / 304 Not Modified in the background under a single-flight page mutex.
  • Zero Reflection & Minimal Binary Size: Pure compile-time typed generics with no runtime reflection, keeping SDK initialization sub-millisecond and footprint tiny.
SDK & Device Budgets
4 Hard Ceilings
L1 Memory & Pool Cap
15–20%

Hard ceiling of app heap budget; trims 75% immediately on OS memory pressure signals.

Decode + L1 Hit
< 12 ms

Keeps 60/120fps scrolling smooth with off-main subsampling and zero GC pauses.

Single-Flight Rate
100%

Zero duplicate in-flight HTTP fetches for identical normalized cache keys.

Core SDK Footprint
< 50 KB

Zero heavy transitive dependencies; host app supplies network and disk adapters.

Act II · Public API Contract & Internal Cache Schema

Pluggable SPI Surface & Disk LRU Journal

Step 2 of 5
Public SDK Contract (SPI & Request Builder)
Zero-Reflection SPI
Cache Key Normalization & Disk LRU Journal (SQLite WAL)
Deterministic Key
Act III · Interactive 5-Node SDK Pipeline & Chaos Switchboard

Coalescing, Cooperative Cancellation & SWR Pagination Simulator

SDK NOMINAL
Step 1 / 6
5-Node SDK Pipeline · Single-Flight Coalescing
4x REQUESTS
view_agenda Host UI & Lifecycle Cells · WxH · GenTag 4 CELLS · GEN #1 call_merge SDK Dispatcher Single-Flight · Mutex COALESCER READY memory L1 Memory & Pool LRU · WeakRef · Pool 24 / 64 MB · WARM hard_drive L2 Disk & Decoder Journal · 2-Pass · Pool DECODER IDLE cloud Network & Page SPI HTTP · ETag · Cursor ADAPTER ONLINE
4x REQUESTS

Loading simulator...

Invariant active
Live Event Console
Live Telemetry HUD
Real-Time
In-Flight Coalesced
4 → 1 req
75% duplicate savings
L1 Memory & Pool
24 / 64 MB
LRU + reusable buffers
Active Decodes
1 / 4 cores
Bounded decode pool
Cancelled / Saved
3 reqs
Zero wasted fetches
Chaos Engineering Switchboard
0 Active
Act IV · Zero-Dependency Kotlin SDK Contracts & Platform Mapping

Library-Agnostic SDK Core & Android / iOS Equivalents

Auto-Synced to Simulator
Platform Mapping Strip (Android & iOS Equivalents) 6 SDK Primitives
Agnostic SDK Primitive Android Equivalent iOS Equivalent
Single-Flight Coalescing CoroutineScope + ConcurrentHashMap<Key, Deferred> Swift Actor + Dictionary<Key, Task>
L1 Memory & Buffer Pool LruCache + BitmapPool (inBitmap) NSCache + ImageIO Downsampling
L2 Disk LRU Cache DiskLruCache / Okio FileSystem URLCache / FileManager LRU Journal
Cooperative Cancellation Job.cancel() + View.doOnDetach Task.cancel() + prepareForReuse()
Pluggable Transport SPI Call.Factory (OkHttp / Ktor) URLSession / Custom Protocol
Cursor Pagination Engine PagingSource / Custom Flow AsyncSequence + Prefetching API
Act V · Architectural Tradeoffs & Production Observability SLOs

SDK Design Tradeoffs & Reliability Targets

Step 5 of 5
Tradeoff 01 Zero Distortion

Cache Key Normalization: Raw URL vs. URL + WxH + Transform

Normalized Key

Hashing url | WxH | scale | transform prevents serving a blurry 64px thumbnail into a 1080px hero banner.

Raw URL Only

Maximizes cache key collisions across sizes, but causes either blurry upscaling or wasteful full-res decoding for tiny avatars.

Verdict: Store raw bytes by URL in L2 Disk, but key decoded bitmaps in L1 RAM strictly by url | WxH | scaleMode | transformHash.

Tradeoff 02 Zero Pool Corruption

Active Image Tracking: Single LRU vs. Active Weak-Ref Map + LRU

Weak-Ref + LRU

Tracks currently displayed bitmaps in an Active Weak-Ref Map so the LRU never recycles a buffer that is still being drawn on screen.

Single LRU Only

Simpler implementation, but evicting a visible bitmap into the buffer pool causes torn frames or native memory crashes.

Verdict: Always separate Active Resources (currently bound to views) from Evictable L1 LRU entries before returning memory to the Bitmap Pool.

Tradeoff 03 Bandwidth Safe

Last-Waiter Cancellation: Immediate Abort vs. Finish-to-Disk

Immediate Abort

When waiter count drops to 0 during a fast fling, aborting the HTTP stream immediately frees radio sockets and decode cores.

Finish-to-Disk

Warms L2 Disk if the user scrolls back, but wastes cellular quota and saturates the 4-6 connection limit on fast flings.

Verdict: Abort immediately when <75% downloaded; optionally allow nearly-finished small assets (>85% complete) to commit to L2 Disk.

Tradeoff 04 Drift-Free

Pagination Contract: Page Numbers vs. Opaque Cursors

Opaque Cursors

Decouples the SDK from backend indexing strategy (keyset, timestamp, search token) and prevents duplicate/skipped items on live inserts.

Page Numbers

Easy to jump to arbitrary page N, but shifts rows whenever new records arrive and forces slow SQL OFFSET scans at scale.

Verdict: Type the pagination SPI generically as PageSource<Key, Item> and default to opaque cursor tokens paired with ETag SWR validation.

Production Observability SLOs
SDK Telemetry Targets
Combined L1+L2 Hit Rate > 88%
Stale Recycled Image Rate 0.00%
Single-Flight Dedup Savings > 35%
Decode OOM / Leak Crash Rate < 0.01%