How would a mobile developer design an efficient and resilient API consumption strategy for a new Flipkart e-commerce application?

FlipkartMobile Developer3–5 YearsAPI Design

7 min readUpdated

Designing an efficient and resilient API consumption strategy for a Flipkart mobile application requires a deep understanding of mobile environment constraints such as varying network conditions, limited battery life, and data costs. The core goal is to minimize network overhead, optimize data transfer, and ensure a smooth, responsive user experience even under suboptimal conditions. This involves a multi-faceted approach focusing on intelligent data fetching, robust error handling, and strategic caching.

Mobile-First API Consumption Considerations

We would start by advocating for lightweight data payloads through techniques like GraphQL or sparse fieldsets in REST, allowing clients to request only necessary data. Data compression (e.g., GZIP) for network requests and responses is crucial to reduce transfer sizes. Network efficiency is further improved by implementing pagination for large lists, request batching for multiple small data fetches, and optimizing image delivery through CDNs and adaptive image formats. We’d also consider using HTTP/2 for multiplexing and header compression to reduce latency.

Best practice

Client-side caching is paramount. This can be implemented at multiple layers: an in-memory cache for short-term data, a disk cache for persistent storage across sessions, and leveraging HTTP caching headers (ETags, Last-Modified) for server-side validation. For resilience, implement robust error handling with exponential backoff and retry mechanisms for transient network issues. An API versioning strategy, preferably through custom headers or path segments, is essential for backward compatibility and smooth evolution of the application without breaking older client versions. Additionally, prioritize asynchronous API calls to prevent UI freezes.

Edge case interviewers probe for

Interviewers often probe on handling intermittent connectivity and offline scenarios. For this, a local-first approach with optimistic UI updates and background data synchronization is key. Data consistency between local cache and server must be managed, potentially using unique identifiers and timestamps for conflict resolution during sync. This also involves managing user sessions and authentication tokens securely in offline states, ensuring re-authentication once connectivity is restored without interrupting the user’s workflow.

Common mistake

A common mistake is treating mobile API consumption like web API consumption, neglecting mobile-specific optimizations. This leads to excessive network requests, large data transfers, and blocking UI operations. Another pitfall is inadequate error handling, where network failures or API errors are not gracefully managed, resulting in crashes or poor user feedback. Relying solely on synchronous calls or neglecting robust caching invalidation also degrades performance and can lead to stale data being displayed to the user.

What the interviewer is checking

The interviewer is checking your ability to think holistically about mobile application performance and resilience. They want to see an understanding of network protocols, caching strategies, error handling, and data optimization techniques tailored to the mobile environment. Your answer should demonstrate a user-centric approach, balancing technical efficiency with a seamless user experience, and show awareness of system design principles like API versioning and fault tolerance in a distributed system.

Imagine you’re at a popular fast-food drive-thru (your mobile app) trying to order for a big family (fetching lots of data). If you ordered one burger, waited for it, then ordered one fry, waited for it, and so on, it would take forever and waste a lot of gas (battery and data). An efficient strategy would be to order all the food at once (batching requests), or if you know you’ll want the same drink every time, you bring your own (caching data locally). You also want to give a simple, clear order so the staff (API) can get it right quickly.

Now, what if the drive-thru’s internet goes down, or they run out of an item? A resilient strategy means your family isn’t starving. You might have some snacks in the car (cached data) to hold them over. If the internet is spotty, you don’t keep shouting your order, you wait a bit then try again politely (retry with backoff). If an item is truly unavailable, the staff tells you clearly so you can pick something else, not just leave you guessing (error handling). This way, even if things go wrong, your family still has a good experience.

Why interviewers ask this

Interviewers ask this to assess your practical understanding of mobile development challenges beyond just coding. They want to know if you can translate business requirements into technical solutions that account for real-world constraints like network variability, battery life, and data costs, which are critical for user retention in e-commerce.

What a strong answer signals

A strong answer demonstrates a comprehensive understanding of mobile-first design principles, performance optimization, and robust error handling. It signals your ability to think critically about user experience, system resilience, and scalability in a mobile context, showing you can build applications that perform well and are reliable.

Common follow-ups

  • How would you handle API authentication and authorization securely in this mobile application?
  • What strategies would you employ for error reporting and logging for API failures on the client side?
  • How would you design for real-time updates (e.g., stock changes, order status) in this API consumption strategy?

Advanced variation

Design an API consumption strategy that supports an “offline-first” experience, where users can browse products, add to cart, and even place orders while disconnected, with seamless synchronization upon reconnection and robust conflict resolution.

Consider a Flipkart product listing page that loads slowly because it fetches a full product object, including high-resolution images and detailed specifications, for every item individually. To optimize, the mobile developer would implement pagination to fetch only a subset of products at a time, use a lightweight API endpoint for the initial list (only product ID, name, thumbnail image), and pre-fetch subsequent pages in the background. Furthermore, product images would be served from a CDN with adaptive resizing, and a client-side disk cache would store product data for faster subsequent access, especially when revisiting categories or specific items.

APIService.swift (Conceptual)
import Foundation

class APIService {
    let baseURL = URL(string: "https://api.flipkart.com/v1")!
    let session: URLSession

    init(session: URLSession = .shared) {
        self.session = session
    }

    func fetchProducts(page: Int, pageSize: Int, completion: @escaping (Result<[Product], Error>) -> Void) {
        var components = URLComponents(url: baseURL.appendingPathComponent("products"), resolvingAgainstBaseURL: true)!
        components.queryItems = [
            URLQueryItem(name: "page", value: "(page)"),
            URLQueryItem(name: "pageSize", value: "(pageSize)"),
            // Optionally add fields for sparse fieldsets: URLQueryItem(name: "fields", value: "id,name,thumbnail")
        ]

        guard let url = components.url else {
            completion(.failure(APIError.invalidURL))
            return
        }

        session.dataTask(with: url) { [weak self] data, response, error in
            guard let self = self else { return }
            if let error = error {
                completion(.failure(APIError.networkError(error)))
                return
            }

            guard let httpResponse = response as? HTTPURLResponse, (200..299).contains(httpResponse.statusCode) else {
                let statusCode = (response as? HTTPURLResponse)?.statusCode ?? 0
                completion(.failure(APIError.serverError(statusCode)))
                return
            }

            guard let data = data else {
                completion(.failure(APIError.noData))
                return
            }

            do {
                let products = try JSONDecoder().decode([Product].self, from: data)
                completion(.success(products))
            } catch {
                completion(.failure(APIError.decodingError(error)))
            }
        }.resume()
    }
}

struct Product: Codable, Identifiable {
    let id: String
    let name: String
    let thumbnailUrl: URL?
    // ... other properties (often fetched from a detailed endpoint)
}

enum APIError: Error {
    case invalidURL
    case networkError(Error)
    case serverError(Int)
    case noData
    case decodingError(Error)
}
Mobile App API Client Client-side Cache CDN / API Gateway Backend Services Database Image/Static Asset Caching
  1. 1Prioritize mobile-specific optimizations like reduced payload sizes, compression, and efficient image delivery to conserve battery and data.
  2. 2Implement a multi-layered caching strategy (in-memory, disk, HTTP caching) to minimize network requests and improve responsiveness.
  3. 3Design robust error handling with retry mechanisms and exponential backoff to ensure resilience against transient network issues.
  4. 4Adopt API versioning and asynchronous communication to ensure backward compatibility, prevent UI freezes, and manage long-term API evolution.
  5. 5Consider offline-first capabilities with optimistic UI updates and background synchronization to enhance user experience during intermittent connectivity.