Networking and Data
1. Networking Fundamentals
Q: Explain the OSI model layers relevant to mobile development.
| Layer | Protocol | Mobile Relevance |
|---|---|---|
| Application (7) | HTTP, WebSocket, gRPC | API communication, JSON/Protobuf parsing |
| Transport (4) | TCP, UDP, QUIC | Reliability (TCP) vs Speed (UDP) |
| Network (3) | IP | Routing packets between devices |
| Link (2) | WiFi, 5G/LTE, Bluetooth | Hardware interface and drivers |
Key Takeaway: Android developers mostly live in Layer 7 (Application), but Layer 4 (Transport) decisions (QUIC/UDP vs TCP) drastically affect app performance on unstable mobile networks.
Q: TCP vs UDP—when would you use each?
| TCP | UDP |
|---|---|
| Connection-oriented | Connectionless |
| Guaranteed delivery, ordering | No guarantees |
| Slower, more overhead | Fast, lightweight |
| HTTP, HTTPS, WebSocket | Video streaming, VoIP, gaming |
Mobile apps typically use TCP (via HTTP) for reliability. UDP for real-time where dropped packets are acceptable.
Q: Explain HTTP/1.1 vs HTTP/2 vs HTTP/3.
| Version | Connection | Key Features |
|---|---|---|
| HTTP/1.1 | One request per connection (or keep-alive) | Sequential, head-of-line blocking |
| HTTP/2 | Multiplexed streams over one connection | Parallel requests, header compression, server push |
| HTTP/3 | QUIC (UDP-based) | Faster handshakes, no TCP head-of-line blocking |
OkHttp supports HTTP/2 by default. HTTP/3 adoption is growing.
Q: What is TLS/SSL and why is it important?
TLS (Transport Layer Security) encrypts communication:
- Confidentiality: Data can't be read in transit
- Integrity: Data can't be modified
- Authentication: Server proves identity via certificate
Android enforces HTTPS by default (cleartext blocked). TLS 1.2+ required for modern apps.
Q: What happens during a TLS handshake?
- Client sends supported cipher suites
- Server chooses cipher, sends certificate
- Client verifies certificate against trusted CAs
- Key exchange (asymmetric) establishes session key
- Symmetric encryption begins
This adds latency; HTTP/2 and HTTP/3 reduce repeat handshakes.
2. REST & API Design
Q: What is REST and its principles?
REST (Representational State Transfer) is an architectural style:
| Principle | Meaning |
|---|---|
| Stateless | Each request contains all needed info |
| Client-Server | Separation of concerns |
| Cacheable | Responses indicate cacheability |
| Uniform Interface | Standard methods (GET, POST, PUT, DELETE) |
| Layered | Client doesn't know if talking to server or intermediary |
Q: Explain HTTP methods and when to use each.
| Method | Purpose | Idempotent | Safe |
|---|---|---|---|
| GET | Retrieve resource | Yes | Yes |
| POST | Create resource | No | No |
| PUT | Replace resource | Yes | No |
| PATCH | Partial update | No | No |
| DELETE | Remove resource | Yes | No |
Idempotent: Same request multiple times = same result Safe: Doesn't modify server state
Q: What are common HTTP status codes?
| Code | Meaning | Action |
|---|---|---|
| 200 | OK | Success |
| 201 | Created | Resource created (POST) |
| 204 | No Content | Success, no body |
| 400 | Bad Request | Client error, fix request |
| 401 | Unauthorized | Need authentication |
| 403 | Forbidden | Authenticated but not allowed |
| 404 | Not Found | Resource doesn't exist |
| 429 | Too Many Requests | Rate limited, backoff |
| 500 | Server Error | Server problem, maybe retry |
| 503 | Service Unavailable | Temporary, retry with backoff |
Q: REST vs GraphQL vs gRPC?
| Aspect | REST | GraphQL | gRPC |
|---|---|---|---|
| Data Format | JSON | JSON | Protobuf (binary) |
| Flexibility | Fixed endpoints | Client specifies fields | Defined services |
| Over-fetching | Common | Solved | N/A |
| Performance | Good | Good | Best (binary) |
| Mobile Use | Most common | Growing | Backend-to-backend, some mobile |
3. WebSocket & Real-Time
Q: When would you use WebSocket instead of HTTP?
| HTTP | WebSocket |
|---|---|
| Request-response | Bidirectional, persistent |
| Client initiates | Either side can send |
| Stateless | Stateful connection |
| Polling for updates | Push updates |
Use WebSocket for: chat, live updates, collaborative editing, gaming.
Q: How does WebSocket work?
- HTTP request with
Upgrade: websocketheader - Server responds 101 Switching Protocols
- Connection upgrades to WebSocket
- Full-duplex communication over same TCP connection
- Either side can close
Q: What alternatives exist for real-time updates?
| Technique | How It Works | Trade-off |
|---|---|---|
| Polling | Repeated HTTP requests | Simple but wasteful |
| Long Polling | Server holds request until data | Better but complex |
| SSE | Server-Sent Events, one-way stream | Simple, HTTP-based |
| WebSocket | Full duplex | Most capable, more complex |
| Push Notifications | FCM/APNs | Works when app closed |
4. Retrofit & OkHttp
Q: Explain the Android networking stack.
The typical stack consists of:
- Retrofit: Type-safe HTTP client. It uses annotations/reflection to generate API code.
- OkHttp: The engine. Handles raw TCP connections, connection pooling, caching, and retries.
- Serialization: Gson, Moshi, or Kotlinx.serialization (KxS) to convert JSON ↔ Objects.
Snippet: Retrofit Interface
interface ApiService {
@GET("users/{id}")
suspend fun getUser(@Path("id") userId: String): User
}
Q: What are interceptors and what types exist?
Interceptors observe, modify, and potentially short-circuit requests/responses.
| Type | Runs When | Use Case |
|---|---|---|
| Application Interceptor | Before OkHttp core | Add headers, logging, modify requests |
| Network Interceptor | After connection established | Access network-level info, redirects |
Common interceptors:
- Authentication: Add auth headers to every request
- Logging: Log request/response for debugging
- Retry: Retry failed requests with backoff
- Caching: Custom cache control
Q: How do you handle authentication token refresh?
Use an Authenticator (not interceptor). When a 401 is received, the authenticator refreshes the token and retries the request. This handles the race condition of multiple simultaneous requests hitting 401.
Q: How do you handle errors?
Map HTTP errors to domain exceptions:
- IOException: Network failures (no connection, timeout)
- HttpException: Server returned error status (401, 404, 500)
Create sealed classes like Result<T> or NetworkResult<T> to represent Success/Error states uniformly.
5. Room Database
Q: What is Room and its components?
Room is Jetpack's SQLite abstraction providing:
- Entity: Data class representing a table (
@Entity). - DAO: Interface for database access (
@Dao). - Database: The main access point (
@Database).
Snippet: Room Basics
@Entity(tableName = "users")
data class User(@PrimaryKey val id: String, val name: String)
@Dao
interface UserDao {
@Query("SELECT * FROM users")
fun getAll(): Flow<List<User>> // Observable query
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insert(user: User)
}
Q: How does Room integrate with reactive streams?
DAOs can return Flow<T> or LiveData<T> for observable queries. When data changes, observers automatically receive updates.
Q: What are common Room annotations?
| Annotation | Purpose |
|---|---|
@Entity |
Define table |
@PrimaryKey |
Primary key column |
@ColumnInfo |
Customize column name |
@Embedded |
Flatten nested object into table |
@Relation |
Define relationship between entities |
@TypeConverter |
Convert custom types to/from SQLite types |
Q: How do you handle database migrations?
Define Migration objects specifying how to alter schema from version N to N+1. Room runs migrations sequentially. If migration is missing, Room throws an exception (fail-safe). Use fallbackToDestructiveMigration() only for development.
Q: What about testing Room?
Use in-memory database for tests:
Room.inMemoryDatabaseBuilder(context, AppDatabase::class.java)
.allowMainThreadQueries() // Only for tests!
.build()
6. DataStore
Q: What is DataStore and how does it differ from SharedPreferences?
DataStore is the modern replacement for SharedPreferences:
| SharedPreferences | DataStore |
|---|---|
| Synchronous (usually) | Fully Async (Coroutines/Flow) |
| Can block Main Thread | Safe for Main Thread (Dispatchers.IO) |
| Runtime errors possible | Type-safe (Proto) or safe keys (Preferences) |
| No transactional support | Atomic read-modify-write operations |
Q: What are the two types of DataStore?
- Preferences DataStore: Key-value pairs, like SharedPreferences but async
- Proto DataStore: Typed objects using Protocol Buffers, schema-defined
Q: When do you use each?
- Preferences DataStore: Like generic
SharedPreferences. Usesedit { settings -> settings[KEY] = value }. - Proto DataStore: Uses a
.protoschema. Guarantee types at compile time.
Snippet: Preferences Keys
val USER_AGE = intPreferencesKey("user_age")
val IS_PREMIUM = booleanPreferencesKey("is_premium")
// Usage: context.dataStore.data.map { prefs -> prefs[IS_PREMIUM] ?: false }
7. Caching Strategies
Q: What caching strategies are common in Android?
| Strategy | Flow | Use Case |
|---|---|---|
| Cache-first | Return cache → fetch network → update cache | News feeds, social content |
| Network-first | Try network → fallback to cache | Critical data, stock prices |
| Cache-only | Only return cache | Offline-first apps |
| Network-only | Always fetch, no cache | Authentication, payments |
| Stale-while-revalidate | Return stale cache → update in background | Best UX for most apps |
Q: How do you implement cache-first with Room + Retrofit?
- Repository observes Room via Flow
- On request, emit cached data immediately
- Fetch from network in parallel
- Insert network data into Room
- Room Flow automatically emits updated data
NetworkBoundResource Pattern:
This is the industry standard for offline-first apps. It exposes a single Flow<Result<Type>> that emits:
Loading → Success(CachedData) → Loading → Success(FreshData).
Q: How do you determine cache validity?
- Timestamp-based: Store fetch time, expire after duration
- ETags: Let server determine if data changed
- Server-provided expiry: Use Cache-Control headers
- Event-based: Invalidate on specific user actions
8. Pagination
Q: How does Paging 3 work?
Paging 3 loads data in chunks as the user scrolls:
| Component | Role |
|---|---|
| PagingSource | Loads pages from single source (network or database) |
| RemoteMediator | Loads network data into database for offline support |
| Pager | Produces PagingData Flow |
| PagingDataAdapter | Submits PagingData to RecyclerView/LazyColumn |
Q: PagingSource vs RemoteMediator?
- PagingSource alone: Simple pagination, network-only or database-only
- RemoteMediator + PagingSource: Offline-first. RemoteMediator fetches network data into DB, PagingSource loads from DB. Best practice for production apps.
Snippet: PagingSource Stub
class UserPagingSource(val api: ApiService) : PagingSource<Int, User>() {
override suspend fun load(params: LoadParams<Int>): LoadResult<Int, User> {
// 1. Load data from network
// 2. Return LoadResult.Page(data, prevKey, nextKey)
}
}
Q: How do you handle errors and retry in Paging?
LoadState contains Loading, NotLoading, and Error states for prepend, append, and refresh. Display loading/error UI based on these states. Provide retry action that calls adapter.retry().
9. Image Loading
Q: What does an image loading library do?
- Async download with disk/memory caching
- Image transformations (resize, crop, round)
- Placeholder and error images
- Lifecycle awareness (cancel on destroy)
- Memory management (avoid OOM)
Q: Coil vs Glide?
| Coil | Glide |
|---|---|
| Kotlin-first, uses coroutines | Java-based, custom threading |
| Lighter, modern | More features, mature |
| Compose integration built-in | Compose support via extension |
| 10KB method count | Larger footprint |
Both are excellent. Coil is preferred for new Kotlin-only projects; Glide for maximum feature set.
Q: How do you optimize image loading?
- Request correct size (don't load 4000px for 100dp view)
- Use appropriate format (WebP for compression)
- Enable hardware bitmaps where supported
- Cache appropriately (memory for frequent, disk for all)
- Preload upcoming images in lists
10. Advanced Scenarios & Security
Q: What is Certificate Pinning?
It defends against Man-in-the-Middle (MitM) attacks by hardcoding the expected server certificate (or public key hash) in the app.
- How: Configure
CertificatePinnerin OkHttp. - Trade-off: If the server rotates keys without app update, the app breaks. Pin the backup keys too.
Q: How do you handle large file downloads?
| Method | Use Case | Pros/Cons |
|---|---|---|
| DownloadManager | Standard system service | Simple, handles retries/notifications, but limited customization. |
| WorkManager | Background download | Precise control, robust constraints (charging/WiFi), works if app killed. |
| Foreground Service | Immediate user focus | Guarantees process stays alive, needed for very active downloads (e.g., podcast player). |
Q: Strategies for Offline Sync Conflicts?
When local data differs from server data:
- Last Write Wins: Server timestamp dictates truth. Simple/Common.
- User Resolution: Prompt user to keep "Local" or "Server" version.
- Merge/diff: Smart merge if fields don't overlap.
Q: JSON Parsing Performance: Reflection vs Code Gen?
- Reflection (Gson): Easiest setup, but slower configuration at runtime. Bad for cold start.
- Code Gen (Moshi-kapt / KxS): Generates adapters at compile time. Faster runtime, smaller footprint, better for large apps.
Q: How does Doze Mode affect networking?
Doze mode defers background network activity when the device is idle to save battery.
- Restrictions: Network access is suspended, wakelocks are ignored, alarms are deferred.
- Solution: Use WorkManager for deferrable jobs (it honors maintenance windows) or FCM High Priority messages for immediate requirements.
Quick Reference
| Topic | Key Points |
|---|---|
| HTTP Basics | TCP for reliability; HTTP/2 for multiplexing; TLS for security |
| REST | Stateless; GET/POST/PUT/DELETE; status codes communicate result |
| WebSocket | Bidirectional; persistent connection; use for chat, live updates |
| Retrofit/OkHttp | Type-safe client; interceptors for headers/logging; Authenticator for 401 |
| Room | Entity + DAO + Database; Flow for reactive queries; migrations for schema |
| DataStore | Async SharedPreferences replacement; Preferences or Proto types |
| Caching | Cache-first for UX; network-first for critical data; Room as cache |
| Paging | PagingSource for simple; RemoteMediator for offline-first; handle LoadState |