MODULE 02 · MOBILE SYSTEM DESIGN

Instagram Feed & Stories

Cursor-driven pagination mediation, velocity-aware media prefetching, and deterministic 24-hour TTL eviction for zero-jank social feeds.

Library-Agnostic 60/120 FPS Budget Offline-First SSOT Android & iOS Mapped
Act I · Scope, Requirements & Device Budget

Functional Targets & Hardware Envelope

Step 1 of 5
Requirements Specification
Core SLAs
Functional Requirements
  • Infinite Offline-First Feed Scroll: Render cached posts immediately from the Local SSOT Database and mediate cursor pages seamlessly.
  • Instant Story Ring Launch (<50ms): Pre-warm the next unseen Story segment so tapping or swiping paints the first frame almost instantaneously.
  • Pull-to-Refresh Without Scroll Jump: Atomically replace stale cursor checkpoints while preserving stable item keys and viewport anchor position.
  • Strict 24h Story Expiration: Enforce deterministic read-time filtering and background disk reclamation so expired media never leaks.
Non-Functional Requirements
  • Zero Dropped Frames During 6,000+ px/s Fast Fling: Velocity-Aware Prefetcher pauses high-res decodes and cancels off-screen work on ballistic flings.
  • Bounded Memory Under OS Memory Pressure: Trim L1 RAM bitmaps aggressively on pressure signals while keeping L2 Disk warm.
  • Graceful Degradation on 3G / High Latency: Fall back to compressed thumbnails, inline BlurHash placeholders, and adaptive prefetch windows.
Device Resource Budget
4 Concrete Caps
L1 RAM Bitmap Pool
48–64 MB

Strict LRU cap with hardware-decoded bitmaps to prevent heap thrashing and GC pauses.

L2 Disk Media Cache
250 MB

Dedicated LRU + TTL partition holding encoded WebP/AVIF frames and 2s Story init segments.

Inline Placeholder
28 Bytes

Compact BlurHash string embedded inside feed JSON for 0.4ms zero-RTT color previews.

Prefetch Window
N+3 / N+1

Velocity-gated N+3 Feed posts ahead of Scroll Viewport and N+1 Story ring segment.

Act II · API, Data Model & Local Storage Contract

Network Payloads & SQLite WAL Schema

Step 2 of 5
Network API Contract (JSON)
Cursor-Mediated
GET /v1/feed?cursor=eyJ0cyI6MTc2MzAxfQ&limit=20
{
  "items": [
    {
      "id": "post_9821",
      "author_id": "usr_402",
      "media_url": "https://cdn.example/p_9821_1080w.webp",
      "aspect_ratio": 0.8,
      "blurhash": "L6PZfSi_.AyE_3t7t7R**0o#DgR4",
      "created_at": 1763018400000
    }
  ],
  "next_cursor": "eyJ0cyI6MTc2MzAxODQwMCwiaWQiOiJwb3N0Xzk4MjEifQ",
  "has_more": true
}
GET /v1/stories/tray
{
  "tray": [
    {
      "author_id": "usr_402",
      "has_unseen": true,
      "segments": [
        {
          "segment_id": "seg_310",
          "media_url": "https://cdn.example/s_310_init.mp4",
          "expires_at_ms": 1763104800000
        }
      ]
    }
  ]
}
Local SSOT Schema (SQLite WAL)
Indexed TTL
-- 1. Ranked home feed table (Single Source of Truth)
CREATE TABLE feed_items (
    id           TEXT PRIMARY KEY,
    rank_index   INTEGER NOT NULL,
    author_id    TEXT NOT NULL,
    media_url    TEXT NOT NULL,
    blurhash     TEXT NOT NULL,
    aspect_ratio REAL NOT NULL,
    fetched_at   INTEGER NOT NULL
);

-- 2. Opaque cursor checkpoints per logical stream
CREATE TABLE feed_cursors (
    stream_key      TEXT PRIMARY KEY,
    next_cursor     TEXT,
    last_refresh_ms INTEGER NOT NULL
);

-- 3. Ephemeral 24h Story segments with indexed expiration
CREATE TABLE story_segments (
    segment_id    TEXT PRIMARY KEY,
    author_id     TEXT NOT NULL,
    media_url     TEXT NOT NULL,
    local_path    TEXT,
    expires_at_ms INTEGER NOT NULL,
    seen          INTEGER NOT NULL DEFAULT 0
);

CREATE INDEX idx_story_exp ON story_segments(expires_at_ms);
Act III · Interactive 5-Node Architecture & Chaos Simulator

Live Topology, Telemetry HUD & Chaos Switchboard

120HZ NOMINAL
Step 1 / 5
5-Node Topology · Cursor Pagination & SSOT
SSOT BIND
UI Viewport Scroll & Story Ring 120Hz · IDLE Pagination & Prefetch Coordinator / Gate READY L1 RAM / L2 Disk Multi-Tier Cache L1 42 MB · WARM Local SSOT DB SQLite WAL + TTL SSOT · READY Edge CDN & API Feed & Media Origin ONLINE · 42ms
SSOT BIND

Loading...

Invariant active
Live Event Console
Live Telemetry HUD
Real-Time
Frame Time
6.4 ms (120Hz)
Within 8.3ms budget
L1 RAM Pool
42 / 64 MB
Strict LRU cap
Prefetch Queue
3 active
N+3 Feed window
Stories Valid / Exp
12 live · 0 exp
0.0% leak guard
Chaos Switchboard
0 Active
Act IV · Library-Agnostic Kotlin Contracts & Platform Mapping

Zero-Dependency Interfaces & Cross-Platform Equivalents

Auto-Synced to Simulator
Platform Mapping Strip (Android & iOS Equivalents) 6 Core Primitives
Agnostic Primitive Android Equivalent iOS Equivalent
Pagination Coordinator Paging 3 (RemoteMediator) Custom AsyncSequence / Diffable Data Source
Local SSOT Database Room / SQLDelight Core Data / SwiftData / GRDB
Multi-Tier Media Cache Coil / Glide (LruCache + DiskLruCache) Kingfisher / Nuke / NSCache
Scroll Velocity Gate LazyListState / RecyclerView OnScrollListener UIScrollViewDelegate / SwiftUI ScrollPhase
OS Memory Pressure ComponentCallbacks2.onTrimMemory didReceiveMemoryWarning / Jetsam
Background TTL Janitor WorkManager (PeriodicWorkRequest) BGProcessingTask (BGTaskScheduler)
Act V · Architectural Tradeoffs & Observability SLOs

Design Decisions & Production Telemetry

Step 5 of 5
Tradeoff 01 O(1) Keyset

Opaque Cursor Pagination vs. Offset (LIMIT/OFFSET)

Opaque Cursor

Keyset seeks stay O(1) at arbitrary depth and never duplicate or drop items when new posts are published.

LIMIT / OFFSET

Simple to prototype, but degrades linearly on deep pages and shifts rows whenever the head of the feed mutates.

Rationale: Social feeds mutate every second. Anchoring pages to opaque cursors persisted in feed_cursors guarantees deterministic continuity.

Tradeoff 02 120Hz Safe

Velocity-Gated Prefetch vs. Eager Viewport Preload

Velocity-Gated

Pauses high-res decodes above 4,500 px/s, cancels off-screen jobs, and preloads N+3 only once reading intent resumes.

Eager Preload

Launches decodes for every transient row during a fast fling, saturating CPU, radio, and the 64 MB L1 RAM cap.

Rationale: Skipping transient frames during ballistic flings preserves the 8.3ms frame budget while cutting wasted cellular bytes by over 60%.

Tradeoff 03 Zero Leak

Atomic Eager + Read-Time TTL Guard vs. Lazy-Only Expiration

Dual TTL Guard

Read-time expires_at_ms > now guarantees 0% UI leaks immediately; periodic janitor reclaims L2 disk blobs safely.

Lazy-Only Eviction

Waits for background jobs or cache misses to expire rows—risking expired Stories appearing after offline sleep.

Rationale: Separate correctness (read-time indexed query) from storage hygiene (background 24h TTL Janitor sweep).

Tradeoff 04 0.4ms Paint

Inline 28B BlurHash vs. Separate Low-Res Thumbnail Request

Inline 28B BlurHash

Ships directly inside feed JSON with zero extra HTTP round-trip; paints color-matched placeholders in 0.4ms.

Separate Low-Res URL

Requires an extra network request and TLS/connection overhead, leaving grey boxes visible on 3G networks.

Rationale: Embedding 28 bytes per post adds <600 bytes per 20-item page while eliminating blank grey placeholders completely.

Production Observability SLOs
Target Telemetry
Scroll Jank Rate < 0.5% frames > 16.6ms
Story First-Frame < 50 ms (p95)
Media Cache Hit Ratio > 88% (L1 + L2)
Expired Story Leak Rate 0.0% post-TTL