Skip to content

Networking


What is Retrofit?

beginner networking retrofit http
View Answer

Retrofit is a type-safe HTTP client for Android built on top of OkHttp.

Retrofit simplifies:

  • REST API integration

  • request creation

  • response parsing

  • serialization/deserialization

Core concepts:

  • interface-based APIs

  • annotations

  • converters

  • coroutine support

๐Ÿš€ See Full Deep Dive


How do Retrofit converters work?

intermediate retrofit serialization networking
View Answer

Retrofit converters handle serialization/deserialization between JSON and Kotlin objects.

Popular converters:

  • GsonConverterFactory

  • MoshiConverterFactory

  • kotlinx.serialization

Converter responsibility:

  • parse response body to objects

  • serialize objects to request body

  • handle content types

  • raise parsing exceptions

๐Ÿš€ See Full Deep Dive


How does Retrofit work with Kotlin Coroutines?

intermediate retrofit coroutines networking
View Answer

Retrofit provides suspend function support for coroutines, eliminating the need for Callback-based APIs.

Advantages:

  • no callback hell

  • structured concurrency

  • cancellation support

  • exception propagation

Under the hood:

  • adapters convert suspend to Call

  • Retrofit wraps in coroutine adapters

  • exceptions throw to caller

  • automatic cancellation on scope exit

๐Ÿš€ See Full Deep Dive


What is an OkHttp Interceptor?

intermediate okhttp networking interceptors
View Answer

Interceptors are OkHttp components that observe/modify HTTP requests/responses.

Two types:

  • Application interceptors: see application code logic

  • Network interceptors: see actual network traffic

Common uses:

  • logging

  • authentication (token injection)

  • request modification

  • response transformation

  • error handling

๐Ÿš€ See Full Deep Dive


How does OkHttp connection pooling work?

intermediate okhttp networking optimization
View Answer

OkHttp maintains a pool of reusable HTTP connections to avoid expensive reconnections.

Benefits:

  • reduced latency

  • better throughput

  • lower CPU/battery usage

  • automatic reuse

How it works:

  • connections cached by host:port:scheme

  • TTL enforced by keep-alive timeout

  • stale connections pruned

  • pool size configurable

๐Ÿš€ See Full Deep Dive


What are REST API principles?

beginner rest api-design networking
View Answer

REST (Representational State Transfer) is an architectural style for building scalable web services.

Core principles:

  • resource-oriented URLs

  • standard HTTP methods

  • stateless communication

  • cacheable representations

  • client-server separation

HTTP methods:

  • GET: retrieve

  • POST: create

  • PUT: replace

  • PATCH: partial update

  • DELETE: remove

๐Ÿš€ See Full Deep Dive


When should you use HTTP PUT vs PATCH?

intermediate rest api-design http
View Answer

PUT and PATCH both modify resources but behave differently.

PUT (complete replacement):

  • replaces entire resource

  • requires full new state

  • idempotent

  • typically 200/204 response

PATCH (partial update):

  • modifies only specified fields

  • doesn't require full state

  • idempotent (with conditionals)

  • more bandwidth-efficient

  • typically 200/204 response

Generally: use PATCH for Android to save bandwidth.

๐Ÿš€ See Full Deep Dive


What are differences between Gson, Moshi, and Kotlin Serialization?

intermediate serialization json performance
View Answer

Three popular JSON serialization libraries for Android.

Gson:

  • reflection-based (slower)

  • no compile-time checks

  • flexible with malformed JSON

  • mature ecosystem

Moshi:

  • reflection + adapters

  • customizable

  • faster than Gson

  • better error messages

Kotlin Serialization:

  • compiler plugin (fastest)

  • compile-time safety

  • no reflection needed

  • newer but growing adoption

๐Ÿš€ See Full Deep Dive


How should you implement authentication in mobile apps?

intermediate authentication security networking
View Answer

Authentication secures API access. Common strategies:

JWT (JSON Web Tokens):

  • token-based (not session-based)

  • include in Authorization header

  • exp claim for expiration

  • refresh token for renewal

OAuth 2.0:

  • delegated access

  • third-party sign-in

  • symmetric exchange flows

  • authorization code flow (mobile)

Best practices:

  • store tokens securely (EncryptedSharedPreferences)

  • use refresh mechanism

  • never hardcode secrets

  • use interceptors for injection

๐Ÿš€ See Full Deep Dive


What is HTTPS and TLS?

beginner security https networking
View Answer

HTTPS encrypts HTTP traffic using TLS (Transport Layer Security).

Benefits:

  • confidentiality (data cannot be read)

  • integrity (data cannot be modified)

  • authentication (server verified)

  • prevents man-in-the-middle attacks

How it works:

  • client initiates TLS handshake

  • server shares certificate

  • symmetric key negotiated

  • encrypted connection established

On Android:

  • HTTPS enforced by default (Network Security Config)

  • certificate validation automatic

๐Ÿš€ See Full Deep Dive


What is certificate pinning?

intermediate security networking okhttp
View Answer

Certificate pinning is a security technique that roots trust in a specific certificate rather than the entire CA hierarchy.

Benefits:

  • prevents compromised CAs

  • blocks rogue certificates

  • cryptographic trust anchoring

How it works:

  • app stores certificate public key

  • validates server cert against pinned key

  • fails if mismatch

OkHttp implementation:

  • CertificatePinner class

  • configure pins in build

  • specify host(s) to pin

  • use wildcard domains if needed

๐Ÿš€ See Full Deep Dive


How should you implement retry logic?

intermediate networking resilience error-handling
View Answer

Retry logic handles transient network failures automatically.

When to retry:

  • network timeouts

  • 5xx server errors

  • connection resets

  • DNS failures

Do NOT retry:

  • 4xx client errors (except 429 rate limit)

  • authentication failures

  • payload errors

Implementation patterns:

  • simple retry with delay

  • exponential backoff

  • jitter to prevent thundering herd

  • max retry limit

๐Ÿš€ See Full Deep Dive


What is exponential backoff?

intermediate networking optimization resilience
View Answer

Exponential backoff increases delay between retries to prevent server overload.

Formula:

delay = base * (2 ^ attempt) + jitter

Benefits:

  • reduces server load

  • prevents thundering herd

  • increases success rate

  • network stabilization

Example:

  • attempt 1: 1s

  • attempt 2: 2s

  • attempt 3: 4s

  • attempt 4: 8s

Best practices:

  • add random jitter

  • set maximum delay

  • set maximum retries

  • respect Retry-After header

๐Ÿš€ See Full Deep Dive


How does pagination work in REST APIs?

beginner pagination rest networking
View Answer

Pagination splits large result sets into smaller pages to reduce memory/bandwidth.

Common approaches:

  • Offset/Limit: offset + limit query params

  • Cursor-based: opaque cursor token

  • Keyset: last ID from previous page

Pagination parameters:

  • page or offset

  • limit or pageSize

  • cursor or pageToken

  • totalCount (optional)

Response:

  • items array

  • hasMore boolean

  • nextPageToken

  • totalCount (optional)

When to use:

  • offset/limit: simple, not ideal for real-time

  • cursor: recommended, handles inserts/deletes

๐Ÿš€ See Full Deep Dive


What is Paging 3 library?

intermediate pagination paging3 android
View Answer

Paging 3 is Android's best-practice pagination library built on Flow for seamless list loading.

Core components:

  • PagingSource: provides page data

  • Pager: creates PagingData Flow

  • PagingDataAdapter: RecyclerView adapter

Benefits:

  • automatic caching

  • cancellation support

  • separation of concerns

  • Flow-based reactive

  • handles duplicate loads

Architecture:

  • repository provides PagingSource

  • viewmodel exposes Pager.flow

  • UI subscribes and displays

๐Ÿš€ See Full Deep Dive


How does HTTP caching work?

intermediate caching http networking
View Answer

HTTP caching reduces bandwidth by reusing responses.

Cache control headers:

  • Cache-Control: max-age (seconds)

  • Expires: absolute time

  • ETag: version identifier

  • Last-Modified: resource timestamp

Caching types:

  • private (browser cache only)

  • public (shared cache)

  • no-cache (validate always)

  • no-store (never cache)

OkHttp caching:

  • automatic by default

  • configurable cache size

  • respects Cache-Control headers

  • offline page fallback possible

๐Ÿš€ See Full Deep Dive


What are ETags and conditional requests?

intermediate caching http optimization
View Answer

ETags and conditional requests minimize bandwidth by validating cached responses.

ETags:

  • unique identifier for resource version

  • server sends with response

  • client includes in future requests

  • server returns 304 Not Modified if unchanged

Conditional requests:

  • If-None-Match: ETag validation

  • If-Modified-Since: timestamp validation

  • server responds 304 Not Modified

  • client reuses cached response

Benefits:

  • save bandwidth

  • validate without full transfer

  • handle resource updates

  • prevent stale data

๐Ÿš€ See Full Deep Dive


What is offline-first architecture?

intermediate offline architecture networking
View Answer

Offline-first prioritizes local-first operation, syncing when network available.

Principles:

  • always use local database first

  • sync to server when connected

  • seamless online/offline transitions

  • user experience consistency

Architecture:

  • local Room database

  • repository handles sync

  • background sync workers

  • conflict resolution

Benefits:

  • instant UI responsiveness

  • works without network

  • resilient to connection loss

  • better battery life

๐Ÿš€ See Full Deep Dive


How do you implement a sync engine?

advanced offline sync architecture
View Answer

A sync engine keeps local and remote data consistent.

Components:

  • sync worker: runs on schedule

  • local database: source of truth

  • remote API: server state

  • conflict resolver: handles mismatches

Sync flow:

  • fetch remote changes (pull)

  • apply to local database

  • upload local changes (push)

  • resolve conflicts

  • mark synced

Challenges:

  • conflict resolution

  • duplicate prevention

  • partial sync recovery

  • offline queue management

๐Ÿš€ See Full Deep Dive


How should you handle sync conflicts?

advanced sync offline architecture
View Answer

Conflict resolution determines which data wins when both local and remote changes exist.

Strategies:

  • last-write-wins: use timestamp

  • remote-wins: server always correct

  • local-wins: device always correct

  • merge: combine changes intelligently

  • manual: show UI for user choice

Implementation:

  • version vectors: track causality

  • timestamps: simple but flawed

  • operation-based: log changes

  • state-based: full state comparison

Production patterns:

  • merge non-conflicting fields

  • use timestamps wisely

  • log conflicts for debugging

  • expose unresolved conflicts in UI

๐Ÿš€ See Full Deep Dive


What are WebSockets?

intermediate websockets networking real-time
View Answer

WebSockets provide full-duplex communication over TCP, enabling real-time bidirectional messaging.

Benefits:

  • persistent connection

  • low latency

  • bidirectional messaging

  • event-driven

  • better than polling

Use cases:

  • chat applications

  • live notifications

  • real-time dashboards

  • multiplayer games

Libraries:

  • OkHttp WebSocket support

  • Scarlet library

  • Kotlin Flows for events

๐Ÿš€ See Full Deep Dive


How do you handle streaming and large file downloads?

intermediate networking streaming optimization
View Answer

Streaming and downloads require special handling to avoid memory issues and provide progress feedback.

Streaming approaches:

  • ResponseBody streaming

  • byte[] chunking

  • reactive publishers

  • progress callbacks

Best practices:

  • write to disk, not memory

  • implement progress listener

  • handle pause/resume

  • validate downloaded file

  • use download manager

Implementation:

  • Retrofit ResponseBody

  • OkHttp interceptors for progress

  • WorkManager for background jobs

  • MediaStore for saved files

๐Ÿš€ See Full Deep Dive


How should you handle network errors?

intermediate error-handling networking resilience
View Answer

Network error handling ensures app gracefully handles connectivity issues and API errors.

Error types:

  • no connectivity

  • timeouts

  • 4xx client errors

  • 5xx server errors

  • parsing errors

Handling strategies:

  • retry transient errors

  • show user-friendly errors

  • log for debugging

  • fallback to cached data

  • offline queue for sync

Response codes:

  • 401: authentication failure

  • 403: permission denied

  • 429: rate limited

  • 5xx: server error (retry)

๐Ÿš€ See Full Deep Dive


What are network resiliency patterns?

advanced resilience networking patterns
View Answer

Resiliency patterns make apps robust to network failures.

Patterns:

  • Circuit breaker: stop retries on repeated failure

  • Bulkhead: isolate failures

  • Timeout: prevent hanging requests

  • Retry: automatic failure recovery

  • Fallback: use cached/default data

Implementation:

  • OkHttp timeouts

  • exponential backoff

  • health checks

  • circuit breaker library (Resilience4j)

Benefits:

  • improved user experience

  • reduced server load

  • cascading failure prevention

  • automatic recovery

๐Ÿš€ See Full Deep Dive


How does request/response compression work?

intermediate optimization networking compression
View Answer

Compression reduces bandwidth by encoding data.

HTTP compression:

  • gzip: most common

  • deflate: less common

  • brotli: newer, better ratio

How it works:

  • client sends Accept-Encoding header

  • server compresses with matching algorithm

  • server sends Content-Encoding header

  • client decompresses

OkHttp:

  • automatic by default

  • transparent to application

  • reduces bandwidth 60-80%

  • minimal CPU overhead

๐Ÿš€ See Full Deep Dive


How do you optimize for battery usage in networking?

intermediate optimization battery networking
View Answer

Battery optimization reduces networking's power consumption.

Techniques:

  • batch requests (not individual)

  • use connection pooling

  • compress responses

  • avoid polling

  • use WorkManager

  • sync intelligently

DON'Ts:

  • frequent network requests

  • polling background services

  • large uncompressed payloads

  • excessive logging

Tools:

  • Battery Historian

  • Perfetto for tracing

  • NetworkProfiler in Studio

๐Ÿš€ See Full Deep Dive


What are differences between GraphQL and REST?

intermediate graphql rest api-design
View Answer

GraphQL and REST are different API design philosophies.

REST:

  • resource-oriented

  • multiple endpoints per domain

  • fixed response structures

  • over/under fetching common

GraphQL:

  • query-oriented

  • single endpoint

  • client specifies fields

  • exact data fetching

  • supports subscriptions

Trade-offs:

REST: simpler caching, broader tooling GraphQL: flexible queries, reduced over-fetching

For Android:

  • REST simpler for mobile

  • GraphQL better for diverse clients

  • Apollo Kotlin library for GraphQL

๐Ÿš€ See Full Deep Dive


What is gRPC?

intermediate grpc networking protocols
View Answer

gRPC is a modern RPC framework using Protocol Buffers and HTTP/2 for efficient communication.

Benefits:

  • faster than JSON/REST

  • strongly typed via protobuf

  • multiplexing with HTTP/2

  • streaming support

  • language-independent

Use cases:

  • microservices

  • high-performance APIs

  • streaming data

  • real-time communication

Complexity:

  • steeper learning curve

  • less browser-friendly

  • newer ecosystem

๐Ÿš€ See Full Deep Dive


How do you monitor and debug network traffic?

intermediate debugging monitoring networking
View Answer

Network debugging reveals actual traffic and helps diagnose issues.

Tools:

  • OkHttp logging interceptor

  • Android Studio Network Profiler

  • Chucker library

  • Stetho library

  • Charles proxy

  • Wireshark

What to log:

  • URL and method

  • request headers

  • response status

  • response time

  • response size

  • errors

Chucker features:

  • intercepts HTTP requests

  • in-app notification

  • request/response inspection

  • replay requests

๐Ÿš€ See Full Deep Dive


How do you handle rate limiting?

intermediate rate-limiting networking resilience
View Answer

Rate limiting controls request frequency per API.

Server communicates limits via headers:

  • X-RateLimit-Limit: max requests

  • X-RateLimit-Remaining: quota left

  • X-RateLimit-Reset: reset timestamp

  • Retry-After: wait before retry

Client-side handling:

  • predict when limit reached

  • queue requests

  • exponential backoff

  • respect Retry-After

  • show user feedback

Implementation:

  • track rate-limit headers

  • use CircuitBreaker pattern

  • queue strategy (FIFO/priority)

๐Ÿš€ See Full Deep Dive


What is idempotency in APIs?

intermediate rest api-design networking
View Answer

Idempotency ensures repeated requests have same effect as single request, crucial for reliability.

Idempotent methods:

  • GET: always safe

  • DELETE: delete again = 204

  • PUT: replace again = same result

Non-idempotent:

  • POST: create again = duplicate

  • PATCH: sometimes idempotent

Implementation:

  • Idempotency-Key header (UUID)

  • server deduplicates by key

  • caches result with key

  • returns cached on retry

Benefits:

  • safe retries

  • conflict prevention

  • exactly-once semantics

๐Ÿš€ See Full Deep Dive


How do you implement multipart file uploads?

intermediate networking file-upload retrofit
View Answer

Multipart uploads handle mixed binary/text data in single request.

Retrofit multipart:

  • @Multipart annotation

  • @Part for file field

  • @Part for text fields

  • RequestBody wrapping

Best practices:

  • compress before upload

  • show progress indicator

  • handle upload resume

  • validate after upload

  • background worker for large

Chunks:

  • upload in chunks

  • resumable upload

  • verify integrity

  • range requests

๐Ÿš€ See Full Deep Dive


How should you version your APIs?

intermediate api-design networking architecture
View Answer

API versioning enables evolution without breaking clients.

Strategies:

  • URL path: /v1/users /v2/users

  • header: Accept: application/vnd.api+v2+json

  • query param: /users?version=2

  • custom header: X-API-Version: 2

Best practices:

  • support 2-3 versions simultaneously

  • provide migration guide

  • deprecate with warning

  • sunset timeline

  • clear documentation

Client-side:

  • respect API version

  • handle version changes

  • migrate gradually

  • test against versions

๐Ÿš€ See Full Deep Dive


What is CDN and when to use it?

intermediate scalability networking cdn
View Answer

CDN (Content Delivery Network) caches content globally for lower latency and bandwidth savings.

Benefits:

  • geographically distributed

  • reduced latency

  • bandwidth savings

  • offload server load

  • DDoS protection

Use cases:

  • static assets (images, JS)

  • video/media streaming

  • mobile app updates

  • download packages

For Android:

  • CDN for APK/updates

  • asset CDN for images

  • API gateway CDN

๐Ÿš€ See Full Deep Dive


How do you cancel network requests?

intermediate networking cancellation coroutines
View Answer

Request cancellation prevents unnecessary network usage and improves responsiveness.

Retrofit with coroutines:

  • automatic cancellation on scope exit

  • respects job.cancel()

  • cleans up OkHttp Call

OkHttp Call:

  • .cancel() method

  • prevents further progress

  • saves bandwidth

  • closes connections

Use cases:

  • navigation away (view destroyed)

  • user explicitly cancels

  • timeout exceeded

  • parent scope cancelled

๐Ÿš€ See Full Deep Dive


What is Network Security Configuration?

intermediate security networking android
View Answer

Network Security Configuration declaratively specifies HTTPS/TLS settings per domain.

Features:

  • enforce HTTPS

  • certificate pinning

  • custom CA certificates

  • domain-specific rules

  • development vs production

Configuration:

  • XML file in res/xml/

  • applied system-wide

  • per-domain override

  • certificate pins

Benefits:

  • prevents MITM attacks

  • gradual certificate migration

  • dev shortcuts (cleartext HTTP)

  • centralized security policy

๐Ÿš€ See Full Deep Dive


How should you configure network timeouts?

intermediate networking optimization okhttp
View Answer

Timeouts prevent indefinite waiting for network responses.

OkHttp timeout types:

  • connectTimeout: TCP connection

  • readTimeout: data arrival

  • writeTimeout: data upload

  • callTimeout: entire call

Configuration:

  • HttpClient.newBuilder().connectTimeout(30, SECONDS)

  • per-request overrides possible

  • consider network conditions

  • balance UX vs resource usage

Android best practices:

  • connection: 10-30 seconds

  • read: 20-60 seconds

  • write: 20-60 seconds

  • retry on timeout

๐Ÿš€ See Full Deep Dive


How do you monitor API performance?

advanced monitoring performance networking
View Answer

Performance monitoring tracks latency, success rates, and resource usage.

Metrics to track:

  • response time distribution

  • success/failure rates

  • error types

  • payload sizes

  • request throughput

Tools:

  • Firebase Performance Monitoring

  • Crashlytics for errors

  • custom analytics

  • server logs

Implementation:

  • timing instrumentation

  • error categorization

  • network state detection

  • batch reporting

๐Ÿš€ See Full Deep Dive