In system design interviews, defining how clients interact with your system during the API step is a foundational component of the delivery framework. API design follows predictable patterns where you select a protocol, define core resources, specify data exchange formats, and establish robust handling for client requests and server responses. Most interviewers assess whether you can establish clean, intuitive contracts and select appropriate communication mechanisms for specific workload constraints.
Try This Problem Yourself
Practice with guided hints and real time AI feedback.
When designing APIs during an interview, apply this structured five step framework to demonstrate systematic engineering decision making:
Requirements & Estimations: Clarify functional and non functional expectations, client diversity, latency bounds, and traffic scale.
Core Entities & Schema Design: Map high level domain objects and identify core resources that reflect underlying database entities.
API Design: Establish protocol selection, resource endpoints, request payloads, query parameter options, and response structures.
High Level Design: Draw the architectural interaction flow connecting clients, API gateways, microservices, and storage layers.
Deep Dives & Production Optimization: Address security protocols, rate limiting, pagination mechanics, idempotency guarantees, and operational trade offs.
Step 1: Requirements & Estimations
Before writing out endpoint signatures or choosing protocols, evaluate the system constraints and client interactions. API design choices directly reflect three architectural drivers:
Client Diversity
Modern architectures serve varied client types. Web applications running on desktop browsers often demand rich aggregate payloads to render comprehensive dashboards in single network round trips. Mobile applications operating on cellular networks prioritize minimal payload sizes and bandwidth conservation to avoid latency bottlenecks. External third party integrations require strict contract stability, explicit versioning, and developer friendly documentation. Internal microservices communicate frequently across datacenter networks, prioritizing low overhead and sub millisecond execution speed.
Traffic Volumes & Throughput
Understanding request throughput dictates protocol choices and networking decisions. High volume public endpoints processing hundreds of thousands of read requests per second necessitate caching friendly protocols and stateless authentication mechanisms. Heavy write pipelines require lightweight serialization formats and asynchronous request handling to prevent connection exhaustion at the gateway tier.
Latency Budget & Connection Persistence
Interactive consumer features like live chat, notification feeds, or financial tickers cannot operate efficiently over standard request response polling loops. Evaluating whether an interaction requires short lived stateless HTTP calls versus long lived persistent socket connections ensures you pick the right communication layer early in the interview.
Step 2: Core Entities & Resource Modeling
Mapping Domain Objects
Successful API design begins by identifying the core entities in your system. Taking an event ticketing system like Ticketmaster as a concrete model, your domain contains distinct entities: events, venues, tickets, and customer bookings.
Good resource modeling maps these entities directly into clear, predictable endpoints. Resources represent nouns within your system rather than action verbs. Use plural nouns for resource paths to maintain consistency across endpoints:
GET/events: Retrieve a list of available events.
GET/events/{id}: Retrieve detailed information for a specific event.
GET/venues/{id}: Fetch venue details and seating arrangements.
GET/events/{id}/tickets: Retrieve available tickets associated with an event.
POST/events/{id}/bookings: Submit a new ticket reservation for an event.
GET/bookings/{id}: Retrieve booking details for a confirmed reservation.
Hierarchical Nesting vs Filtering
When modeling relationships between entities, choose between nested resource paths and top level query filters based on whether the relationship is strictly required:
Nested Resource Paths: Use path parameters when a parent entity is strictly required to identify or isolate child records. For example, accessing /events/{id}/tickets makes semantic sense because tickets exist inherently within the context of a specific event.
Top Level Query Parameters: Use query parameters when filtering resources across optional criteria or global collections. For example, querying /tickets?event_id=123§ion=VIP allows clients to apply flexible combinations of optional filters without forcing artificial deep nesting.
Step 3: API Design & Protocol Selection
Protocol Selection Comparison
In a system design interview, you will evaluate three primary API communication protocols:
1. REST (Representational State Transfer)
REST relies on standard HTTP semantics, operating on resources identified by uniform resource locators. It utilizes standard HTTP verbs (GET, POST, PUT, PATCH, DELETE) to manipulate underlying entities, returning structured representations (typically JSON).
Best Used For: Standard CRUD operations across public web and mobile applications. It maps naturally to relational database records and standard web infrastructure.
Interview Guidance: Make REST your default recommendation unless clear application requirements demand specialized alternatives. It is universally understood and fast to articulate.
2. GraphQL
GraphQL consolidates resource endpoints into a single unified execution endpoint. Clients submit queries explicitly specifying the exact nested attributes they require, and the server returns data matching that exact structural shape.
Best Used For: Applications supporting diverse clients (such as feature lean mobile apps alongside analytics heavy web dashboards) where flexible data fetching prevents network payload bloat.
Trade Offs: While GraphQL eliminates over fetching and under fetching, it introduces server side complexity. Queries require dynamic parsing, caching becomes challenging due to POST based request wrapping, and resolvers risk encountering the N+1 query problem during database retrieval.
3. RPC & gRPC (Remote Procedure Call)
RPC abstracts network calls into function invocations, framing interactions as actions rather than resource manipulations (for example, invoking checkPermission(userId,resourceId)). Modern RPC implementations like gRPC utilize Protocol Buffers for binary serialization over HTTP/2 multiplexed streams.
Best Used For: High performance internal microservice communication, inter service telemetry, and streaming data pipelines.
Trade Offs: Binary payloads are not natively human readable in browser debugging tools, requiring client code generation from contract definition files (.proto).
HTTP Verbs & Idempotency Rules
Understanding HTTP method semantics and idempotency guarantees is essential when designing RESTful interfaces:
GET: Retrieves resources without modifying server state. Safe and idempotent.
POST: Submits new data to create resources. Neither safe nor idempotent. Executing identical POST requests sequentially creates duplicate server resources.
PUT: Replaces an existing resource entirely or creates it if absent. Idempotent because repeated submissions of identical state yield identical server records.
PATCH: Applies partial updates to an existing resource. Idempotency depends on implementation logic. Setting a field value directly is idempotent, whereas appending elements to an array is not.
DELETE: Removes a resource. Idempotent because repeated invocations leave the system in an identical state where the specified resource remains absent.
Data Passing Mechanics
APIs receive input across three distinct channels based on parameter scope:
Path Parameters: Identify specific, required resource instances in structural URLs (for example, /events/123).
Query Parameters: Supply optional filtering, sorting, or pagination modifiers (for example, /events?city=NYC&limit=10).
Request Payload Body: Encapsulates complex, multi attribute objects during creation or update operations (for example, JSON arrays passed during POST booking submissions).
HTTP Status Code Conventions
Group responses logically into standard HTTP status categories:
200 OK: Request completed successfully.
201 Created: Resource created successfully following a POST request.
400 Bad Request: Malformed request payload or invalid parameter inputs.
401 Unauthorized: Missing or invalid authentication credentials.
403 Forbidden: Authenticated user lacks authorization permissions for the target resource.
404 Not Found: Target resource identifier does not exist.
429 Too Many Requests: Client exceeded designated rate limiting thresholds.
500 Internal Server Error: Unexpected server side exception.
Step 4: High Level Design
Architectural interaction flow illustrating client applications connecting through unified edge gateways to internal microservices, caching layers, and persistence stores.
Architecture Diagram Generation Prompt: Create a detailed architecture diagram illustrating a complete API subsystem for a high scale event ticketing and reservation platform. Show client tiers including Mobile Applications, Web Dashboards, and Third Party Partner Integration API clients connecting to a unified API Gateway layer. Illustrate the API Gateway handling TLS termination, rate limiting, and JWT token authentication. Behind the gateway, depict external REST endpoints routing to fronting services while high throughput microservices communicate internally via gRPC RPC connections over HTTP/2. Show services interacting with PostgreSQL read replicas for event discovery, an In Memory Redis cluster for seat availability caching, and Apache Kafka for asynchronous booking event streams.
Step 5: Deep Dives & Real World Production Case Studies
Common API Design Patterns
Pagination Strategies
When querying extensive data collections, returning complete datasets saturates bandwidth and exhausts database memory. Select between two primary pagination strategies:
Offset Based Pagination: Clients pass skipping offsets and page limits (for example, /events?offset=20&limit=10). It is simple to implement in SQL (LIMIT10OFFSET20), but degrades in performance on deep offsets because the database engine must scan and discard preceding rows. Additionally, real time insertions or deletions cause data shifting, leading to duplicate or skipped records between pages.
Cursor Based Pagination: Clients pass an opaque pointer referencing the final record from the prior page (for example, /events?cursor=cmd9atj3&limit=10). The server queries records immediately following that cursor position using indexed columns (WHEREid>cursorLIMIT10). This provides stable sequential scanning invariant to real time writes and maintains high query performance on massive datasets.
Versioning Strategies
APIs evolve over time, requiring strategies to update data contracts without breaking legacy client applications:
URL Path Versioning: Explicitly embed version identifiers directly in the request path (for example, /v1/events or /v2/events). This approach is highly visible, easy to route across distinct service clusters, and represents the industry standard for system design interviews.
Header Versioning: Clients specify target API versions using custom HTTP request headers (for example, Accept-Version:v2). This maintains clean, persistent URL paths but introduces routing complexity at gateway proxy layers.
Security Considerations
Authentication vs Authorization
Authentication: Verifies request origin and proves identity (confirming that a user or service is who they claim to be).
Authorization: Enforces permission policies (confirming that an authenticated user possesses valid access rights to modify a specific resource).
API Keys vs JWT Tokens
Choose authentication mechanisms based on client consumer characteristics:
API Keys: Cryptographically generated long random strings passed inside request headers (for example, Authorization:Bearersk_live_abc123...). Ideal for server to server communication, background cron jobs, and third party developer programmatic access where keys are stored securely in vault configurations.
JWT (JSON Web Tokens): Signed, cryptographically verifiable tokens containing encoded user claims (user identifier, assigned roles, token expiration timestamps). Because services verify signatures independently using shared public keys or HMAC secrets, JWT tokens enable stateless session validation across distributed microservices without requiring centralized database lookups.
Role Based Access Control (RBAC) & Rate Limiting
Role Based Access Control: Assigns explicit permissions to user roles (such as customer, venue manager, administrator), checking authorization rules at service interceptors prior to handler execution.
Rate Limiting & Throttling: Protects downstream infrastructure from traffic surges and abuse by tracking request counts per user identifier or client IP address at the API Gateway layer, returning standard HTTP 429 status codes upon threshold breach.
Real World Production Case Studies
1. High Scale Event Ticketing Platform
Handling flash sales for popular concerts requires preventing seat overselling while maintaining high reservation throughput.
Idempotency Keys: Clients generate unique UUID idempotency tokens for booking submissions (POST/events/{id}/bookings), passing them in request headers (Idempotency-Key:c9a8...). The API gateway checks an in memory Redis cache to ensure retried network requests execute booking logic exactly once.
Two Phase Reservations: Split reservations into temporary seat holds via high speed Redis TTL keys, followed by asynchronous payment processing before confirming permanent database rows.
2. Polyglot Microservice Architecture
Large enterprise engineering teams build specialized microservices using distinct programming languages suited for specific workloads.
Edge Gateway Routing: Public traffic enters via an NGINX or Envoy edge gateway using REST over HTTPS, providing developer friendly JSON interfaces for mobile apps and browser clients.
Internal gRPC Mesh: Microservices communicate internally using gRPC and Protocol Buffers over HTTP/2 multiplexed TCP streams. This eliminates JSON parsing overhead, guarantees compile time contract verification across polyglot codebases, and minimizes inter service network latency.
3. Cross Platform Content Streaming Network
Digital media platforms deliver content across smart TVs, low bandwidth mobile devices, and high resolution desktop browsers.
GraphQL Federation: Utilize a federated GraphQL gateway layering over underlying microservices. Mobile clients query lean payload subsets containing basic titles and thumbnail URLs, whereas desktop clients request comprehensive metadata, actor biographies, and interactive recommendations in single network round trips.
Dataloader Query Batching: Implement server side batching resolvers using DataLoader utilities to collapse concurrent field queries into consolidated SQL batch fetches, completely eliminating N+1 database performance bottlenecks.
Summary Checklist for System Design Interviews
Identify Client Types: Evaluate whether public consumers require REST or GraphQL, and whether internal microservices require gRPC.
Model Noun Resources: Establish plural, intuitive resource paths representing domain entities rather than action procedures.
Apply Proper HTTP Verbs: Match operations cleanly with standard methods and enforce strict idempotency guarantees.
Implement Robust Pagination: Recommend cursor based pagination for real time streams or massive collections to maintain stable performance.
Enforce Security Boundaries: Implement JWT tokens for stateless user sessions, enforce role based access controls, and protect endpoints with gateway rate limiting.