← Back to Interview Prep
🔌

REST API & Microservices Q&A

50 scenario-based interview questions covering REST principles, HTTP methods, API security (JWT/OAuth), and microservices architecture patterns.

10 REST Basics10 API Design10 Authentication10 Microservices10 Scaling & Arch
1

REST Fundamentals & HTTP

Q1.What is REST and what are its key principles?

  • REST (Representational State Transfer) is an architectural style for designing networked applications.
  • Key principles: 1. Client-Server architecture. 2. Statelessness (no client context stored on server between requests).
  • 3. Cacheability. 4. Uniform Interface (standard HTTP verbs/URIs). 5. Layered system. 6. Code on demand (optional).

Q2.What is the difference between GET and POST?

  • GET is used to retrieve data. It is idempotent (safe to call multiple times without side effects). Parameters are sent in the URL string. Can be cached.
  • POST is used to create new data or submit data for processing. It is NOT idempotent. Data is sent in the request body. Not cached by default.

Q3.What is the difference between PUT and PATCH?

  • Both are used for updating resources.
  • PUT completely replaces an entire resource with the payload provided. It is idempotent.
  • PATCH applies partial modifications to a resource (only updating the fields provided). It is not strictly idempotent by definition.

Q4.What does it mean for an API to be stateless?

  • Statelessness means that every request from the client to the server must contain all the information necessary to understand and process the request.
  • The server does not store any session state about the client. This makes scaling easier since any server can handle any request.

Q5.Explain the most common HTTP status codes returned by a REST API.

  • 200 OK (Success for GET/PUT/PATCH), 201 Created (Success for POST), 204 No Content (Success for DELETE).
  • 400 Bad Request (Invalid input), 401 Unauthorized (Missing/invalid auth), 403 Forbidden (Auth OK, but lacking permissions), 404 Not Found.
  • 500 Internal Server Error (Server crashed/bug), 503 Service Unavailable (Overloaded/down).

Q6.What is a URI vs a URL?

  • URI (Uniform Resource Identifier) is a string of characters that identifies a resource (e.g., urn:isbn:0451450523).
  • URL (Uniform Resource Locator) is a specific type of URI that not only identifies a resource but provides a means of locating it (e.g., https://api.example.com/users).
  • All URLs are URIs, but not all URIs are URLs.

Q7.Why should you version your REST API and how do you do it?

  • Versioning ensures that changes to the API don't break existing clients.
  • Methods: 1. URI path (e.g., /api/v1/users). 2. Query parameter (e.g., /users?version=1).
  • 3. Custom Header (e.g., `X-API-Version: 1`). 4. Accept Header (Content Negotiation, e.g., `Accept: application/vnd.company.v1+json`).

Q8.What is HATEOAS in REST?

  • HATEOAS (Hypermedia As The Engine Of Application State) is a constraint of the REST architecture.
  • A REST client needs no prior knowledge about how to interact with an application beyond a generic understanding of hypermedia.
  • The server returns links dynamically in the API response (e.g., a "next_page" link) to guide the client on what actions are available next.

Q9.What are Idempotent HTTP methods?

  • An idempotent method means that making multiple identical requests has the same effect on the server as making a single request.
  • Idempotent: GET, PUT, DELETE, HEAD, OPTIONS.
  • Non-idempotent: POST (making it twice creates two resources), PATCH (usually).

Q10.How do you handle pagination in a REST API?

  • Since returning thousands of records is slow, APIs use pagination.
  • Offset-based: `?limit=20&offset=40` (Easy to implement, but slow for large offsets and can miss/duplicate items if data changes).
  • Cursor-based: `?cursor=xyz123` (Fast and stable, commonly used by modern large-scale APIs like Twitter/Stripe).
2

API Design & Best Practices

Q11.How would you design an API endpoint to update a user's email?

  • Method: PATCH (since we are partially updating the user).
  • URI: `/api/v1/users/{userId}`
  • Body: `{ "email": "new@email.com" }`
  • Response: 200 OK with the updated user object, or 204 No Content.

Q12.What is GraphQL and how does it compare to REST?

  • GraphQL is a query language for APIs developed by Facebook.
  • REST has multiple endpoints for different resources and often suffers from over-fetching (getting more data than needed) or under-fetching (needing multiple requests).
  • GraphQL has a single endpoint. The client specifies exactly what data it wants in a single query, solving over/under-fetching.

Q13.What is gRPC and when would you use it over REST?

  • gRPC is a high-performance RPC framework by Google using HTTP/2 and Protocol Buffers (Protobuf).
  • It is much faster and uses a binary format rather than JSON text.
  • Use gRPC for internal microservice-to-microservice communication where speed and low latency are critical. Use REST for public-facing APIs.

Q14.How do you handle errors in a REST API?

  • Always return the appropriate standard HTTP status code.
  • Return a consistent JSON payload containing details.
  • Example: `{ "error": { "code": "VALIDATION_FAILED", "message": "Email is required", "details": [...] } }`

Q15.What is Rate Limiting and why is it important?

  • Rate limiting restricts the number of API requests a client can make in a given timeframe (e.g., 100 requests per minute).
  • Importance: Protects the API from DDoS attacks, prevents abuse, ensures fair usage among clients, and helps manage server load/costs.

Q16.How do you implement caching in a REST API?

  • Use HTTP cache headers.
  • `Cache-Control`: Specifies max-age (e.g., `Cache-Control: max-age=3600` caches for 1 hour).
  • `ETag`: A unique hash of the resource. Client sends `If-None-Match: <etag>`. If unchanged, server returns 304 Not Modified (empty body).

Q17.What is Webhook?

  • A webhook is a user-defined HTTP callback.
  • Instead of the client continuously polling an API to see if an event happened (pull), the API sends an HTTP POST request to a URL provided by the client when the event occurs (push).
  • Example: Stripe sends a webhook to your server when a payment succeeds.

Q18.How should you name REST API endpoints?

  • Use nouns to represent resources, not verbs (e.g., `/users`, not `/getUsers`).
  • Use plural nouns for collections (`/users`, `/orders`).
  • Use hierarchy for nested resources (`/users/123/orders/456`).
  • Use kebab-case for multi-word paths (`/user-profiles`).

Q19.How do you secure a REST API?

  • Use HTTPS (TLS) for all communication.
  • Implement Authentication (OAuth 2.0, JWT) and Authorization (RBAC).
  • Use Rate Limiting/Throttling.
  • Validate all input data to prevent SQL Injection/XSS.
  • Don't expose internal IDs if possible (use UUIDs).

Q20.What is API documentation and which tools are standard?

  • API documentation tells developers how to use the API (endpoints, params, responses, errors).
  • OpenAPI (formerly Swagger) is the industry standard specification for defining REST APIs.
  • Tools like Swagger UI or Postman are used to generate interactive documentation.
3

Authentication & Security

Q21.What is the difference between Authentication and Authorization?

  • Authentication (AuthN) verifies WHO the user is (e.g., checking username/password).
  • Authorization (AuthZ) verifies WHAT the user is allowed to do (e.g., checking if the user has admin role to delete a post).

Q22.What is a JWT (JSON Web Token) and how does it work?

  • JWT is a standard for securely transmitting information between parties as a JSON object.
  • It consists of 3 parts separated by dots: Header (alg), Payload (claims/user data), and Signature (verifies token wasn't altered).
  • It is stateless—the server verifies the signature using a secret key without needing to look up the token in a database.

Q23.What are the pros and cons of using JWT?

  • Pros: Stateless (highly scalable, no database hit required to verify), compact, easy to pass in headers.
  • Cons: Cannot be easily revoked before expiration (unlike session IDs), payload is encoded but NOT encrypted (anyone can read the claims), size can get large if too many claims are added.

Q24.How do you securely store JWTs on the client side (browser)?

  • Storing in `localStorage` or `sessionStorage` is vulnerable to XSS (Cross-Site Scripting) attacks, as JavaScript can read them.
  • Best practice: Store the JWT in an `HttpOnly`, `Secure`, `SameSite` cookie. This prevents client-side JS from reading it, mitigating XSS.

Q25.What is OAuth 2.0?

  • OAuth 2.0 is an industry-standard authorization framework.
  • It allows a user to grant a third-party application limited access to their resources (like their Google profile) without sharing their password.
  • Common flows: Authorization Code (for web apps), Client Credentials (for server-to-server).

Q26.What is the difference between an Access Token and a Refresh Token?

  • Access Token: A short-lived token (e.g., 15 mins) used to access protected resources.
  • Refresh Token: A long-lived token (e.g., 30 days) used to request a new Access Token when the old one expires, without forcing the user to log in again.
  • Refresh tokens must be securely stored (usually in a DB) and can be revoked.

Q27.Explain CSRF (Cross-Site Request Forgery) and how to prevent it.

  • CSRF is an attack where a malicious site tricks a user's browser into sending a forged request (with cookies attached) to a trusted site where the user is logged in.
  • Prevention: Use Anti-CSRF tokens (a unique hidden value sent with forms) or the `SameSite` cookie attribute to prevent cookies from being sent in cross-site requests.

Q28.What is CORS (Cross-Origin Resource Sharing)?

  • A browser security feature that restricts web pages from making API requests to a different domain than the one that served the web page (Same-Origin Policy).
  • To allow it, the API server must include specific CORS headers (e.g., `Access-Control-Allow-Origin: *`) in its preflight (OPTIONS) and standard responses.

Q29.What is Basic Authentication?

  • The simplest form of auth. The client sends the HTTP `Authorization` header containing the word `Basic` followed by a base64-encoded string of `username:password`.
  • Because it is easily decoded, it MUST only be used over HTTPS. Generally replaced by Token-based auth for modern APIs.

Q30.What is SSO (Single Sign-On)?

  • An authentication scheme that allows a user to log in with a single ID and password to access multiple related, yet independent, software systems.
  • Protocols like SAML, OAuth2, and OpenID Connect (OIDC) power SSO (e.g., "Log in with Google" or corporate Okta setups).
4

Microservices Architecture & Patterns

Q31.What is Microservices Architecture?

  • An architectural style that structures an application as a collection of small, autonomous services modeled around a business domain.
  • Each service runs its own process, manages its own database, and communicates with others via lightweight mechanisms (REST, gRPC, or messaging queues).

Q32.What is a Monolithic Architecture and why move away from it?

  • Monolith: All code (UI, business logic, DB access) is tightly coupled into a single deployable unit.
  • Why move away: As the codebase grows, monoliths become hard to understand, slow to build/deploy, scaling requires scaling the whole app, and you are locked into a single technology stack.

Q33.What are the main challenges of using Microservices?

  • Increased operational complexity (deploying and monitoring many services).
  • Network latency and handling partial failures (what if service A calls service B, but B is down?).
  • Data consistency (distributed transactions are hard; no simple SQL joins across services).
  • Debugging tracing requests across multiple services.

Q34.How do microservices communicate with each other?

  • Synchronous: REST API over HTTP, or gRPC. (Service A waits for Service B to respond).
  • Asynchronous/Event-Driven: Message brokers like Kafka, RabbitMQ, or AWS SQS. (Service A publishes an event, Service B consumes it whenever ready). Async is preferred for loose coupling.

Q35.What is the API Gateway pattern?

  • An API Gateway sits between the clients (web/mobile) and the internal microservices.
  • It acts as a reverse proxy, routing requests to the correct service.
  • Responsibilities: Authentication, rate limiting, SSL termination, request routing, and aggregating responses from multiple services into one payload for the client.

Q36.What is the Saga Pattern?

  • A pattern used to manage distributed transactions across microservices.
  • Since you can't use traditional ACID transactions across different databases, a Saga splits the transaction into local transactions.
  • If one local transaction fails, the Saga executes compensating transactions to undo the changes made by the preceding steps (e.g., refunding payment if inventory fails).

Q37.What is the Circuit Breaker pattern?

  • A pattern to prevent catastrophic cascading failures.
  • If Service B is down, Service A should not endlessly wait or keep sending requests (which wastes resources).
  • The Circuit Breaker detects the failure threshold, "trips" (opens the circuit), and immediately returns an error or fallback response for subsequent requests, giving Service B time to recover.

Q38.What is the Service Discovery pattern?

  • In cloud environments, microservices are dynamic—their IP addresses change constantly as they scale up/down.
  • Service Discovery (e.g., Consul, Eureka, or Kubernetes internal DNS) keeps a registry of available services and their current IPs, allowing services to find and call each other by name rather than hardcoded IPs.

Q39.What is CQRS?

  • Command Query Responsibility Segregation.
  • A pattern that separates the read model (Queries) from the write/update model (Commands).
  • Often used with event sourcing, allowing you to scale read databases (e.g., Elasticsearch for fast searching) independently from write databases (e.g., PostgreSQL for transactions).

Q40.What is the Database-per-Service pattern?

  • A core rule of microservices: Each microservice must have its own private database.
  • Other services cannot access that database directly; they must go through the service's API.
  • Ensures loose coupling—if one team changes their database schema, it doesn't break another team's service.
5

Scaling, Gateways & Service Mesh

Q41.What is the difference between horizontal and vertical scaling?

  • Vertical Scaling (Scale Up): Adding more CPU, RAM, or Disk to an existing single server. Limited by hardware ceilings.
  • Horizontal Scaling (Scale Out): Adding more servers/nodes to a pool and distributing the load across them. Preferred in modern cloud/microservices architectures for high availability.

Q42.What is a Load Balancer?

  • A device or software (like Nginx, HAProxy, AWS ALB) that distributes incoming network traffic across a group of backend servers.
  • It ensures no single server bears too much demand, improving responsiveness and availability (if a server dies, the LB stops sending traffic to it).

Q43.Explain Sticky Sessions in Load Balancing.

  • Normally, an LB distributes requests round-robin.
  • Sticky Sessions (Session Affinity) forces the LB to route all requests from a specific user (based on a cookie or IP) to the exact same backend server.
  • Often an anti-pattern. Modern APIs should be stateless, storing session data in a distributed cache like Redis, so any server can handle the request.

Q44.What is a Service Mesh?

  • A dedicated infrastructure layer for handling service-to-service communication in a microservices architecture.
  • Instead of hardcoding retry logic, circuit breakers, and mTLS security into the application code, a Service Mesh (like Istio or Linkerd) injects a "sidecar" proxy next to each container to handle these networking concerns automatically.

Q45.What is Auto-scaling?

  • A cloud computing feature that automatically adjusts the number of active servers or containers based on current load metrics.
  • Example: If average CPU usage exceeds 70%, automatically add 2 more EC2 instances or Kubernetes Pods. Scale back down when traffic drops to save costs.

Q46.What is eventual consistency?

  • In distributed databases or microservice event-driven systems, changes are not instantaneously visible to all nodes.
  • Eventual consistency guarantees that, if no new updates are made to a given piece of data, eventually all accesses to that item will return the last updated value.
  • TRade-off made for higher availability and partition tolerance (CAP theorem).

Q47.How do you handle trace logging across microservices?

  • Use Distributed Tracing (e.g., Jaeger, Zipkin, OpenTelemetry).
  • The API Gateway generates a unique `Correlation ID` (or Trace ID) and passes it in the HTTP headers to the first service.
  • Every subsequent service passes that ID along and includes it in their logs, allowing you to stitch the entire request path together.

Q48.What is a message broker and when do you use it?

  • A middleware (like Apache Kafka, RabbitMQ) that enables applications to communicate by sending and receiving messages asynchronously.
  • Used to decouple services, handle traffic spikes (buffering messages in a queue), and implement publish-subscribe patterns.

Q49.What is caching and where can it be applied?

  • Storing copies of frequently accessed data in a fast, temporary storage (like Redis or Memcached) to reduce database load and latency.
  • Can be applied at: Client (browser), CDN (edge), API Gateway, Application level (Redis), or Database level.

Q50.What is rate limiting vs throttling?

  • Rate Limiting: Determines how many requests a user can make in a time window (e.g., 100/min). If exceeded, returns 429 Too Many Requests.
  • Throttling: Rather than outright blocking the request, throttling slows down the processing of the requests to match the server capacity, smoothing out traffic spikes.

🔌 Pro Tip for System Design Interviews

When discussing microservices, always mention how you handle failures (Circuit Breakers, Retries) and trace requests (Correlation IDs). Reliability is key!

← Back to All Interview Guides