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
Transport (4) TCP, UDP Reliability vs speed
Network (3) IP Routing, addressing
Link (2) WiFi, Cellular Connection type affects behavior

Most Android work happens at Application layer; understanding Transport helps with optimization.

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?

  1. Client sends supported cipher suites
  2. Server chooses cipher, sends certificate
  3. Client verifies certificate against trusted CAs
  4. Key exchange (asymmetric) establishes session key
  5. 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?

  1. HTTP request with Upgrade: websocket header
  2. Server responds 101 Switching Protocols
  3. Connection upgrades to WebSocket
  4. Full-duplex communication over same TCP connection
  5. 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, converts API endpoints to Kotlin interfaces
  • OkHttp: Underlying HTTP client handling connections, caching, interceptors
  • Gson/Moshi/Kotlinx.serialization: JSON parsing

Retrofit uses OkHttp internally. You configure OkHttp with interceptors and timeouts, then pass it to Retrofit.

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 with SQL queries (@Dao, @Query, @Insert)
  • Database: Abstract class holding DAOs (@Database)

Room generates implementation at compile time, catches SQL errors early.

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 API Async (Flow-based)
Can block main thread Never blocks
No type safety Type-safe with Proto DataStore
Exception handling unclear Exceptions in Flow
No transaction guarantees Transactional

Q: What are the two types of DataStore?

  1. Preferences DataStore: Key-value pairs, like SharedPreferences but async
  2. Proto DataStore: Typed objects using Protocol Buffers, schema-defined

Q: When do you use each?

  • Preferences DataStore: Simple settings, feature flags, user preferences
  • Proto DataStore: Complex structured data, type safety critical
  • Room: Relational data, complex queries, multiple tables

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?

  1. Repository observes Room via Flow
  2. On request, emit cached data immediately
  3. Fetch from network in parallel
  4. Insert network data into Room
  5. Room Flow automatically emits updated data

This gives instant UI with fresh data arriving shortly after.

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.

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

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

results matching ""

    No results matching ""