PadhaikoAll subjects

Web Services and APIs

Web Application Programming (ENCT 302)

Open in the Padhaiko app

4.1 API basics: Role in web applications

An Application Programming Interface (API) is a formal contractual specification of rules, protocols, and data formats through which distinct software systems communicate. In distributed web engineering, a Web Service or Web API provides programmatic access to server-side business logic and persistent data over standard Internet transport protocols (primarily HTTP/HTTPS).

Definition

Web API

A Web API is a network-accessible software interface that defines a structured set of endpoints (URIs), supported HTTP request methods, acceptable request payload schemas, and resulting response formats. It enables heterogeneous client runtimes to perform operations and query state without knowledge of the server's internal database schemas or programming language.

Critical Roles of APIs in Modern Web Architecture

  1. Decoupling Front-End Presentation from Backend Logic: In modern architectures, backends function as "headless" service providers. A single unified Web API serves multiple client consumers simultaneously: browser-based Single Page Applications (React/Vue), native mobile applications (iOS/Android), desktop clients, and IoT smart devices.
  2. Third-Party Ecosystem Integration: APIs enable enterprise applications to integrate external capabilities without building complex sub-systems from scratch:
    • Payment Gateways: eSewa, Khalti, Stripe, and PayPal for handling financial transactions.
    • Identity Providers: Social OAuth 2.0 login through Google, GitHub, and Microsoft.
    • Communication Services: Automated SMS notifications (Sparrow SMS) and transactional emails (SendGrid).
    • Mapping & Geolocation: Google Maps API for campus navigation and route tracking.
  3. Enterprise System Federation: Large institutions (such as Tribhuvan University) partition operations into specialized autonomous departments (admissions, fee collection, central library, examination division). APIs allow disparate legacy and modern software packages to synchronize records securely.

Architectural Evolution of Web Services

Evolutionary Comparison of Web API Paradigms
API ParadigmTransport & SerializationArchitectural PhilosophyTypical Use Cases
RPC (XML-RPC, JSON-RPC)HTTP / TCP using XML or JSONAction-oriented: Invokes remote procedures like local functions (getUser(id))Internal commands, legacy inter-process calls
SOAP (Simple Object Access Protocol)HTTP / SMTP using strict XML + WSDLProtocol-driven: Strict contracts, enterprise WS-Security, ACID transactionsBanking, telecommunications, government integrations
REST (Representational State Transfer)HTTP using JSON / XMLResource-oriented: Leverages native HTTP verbs on identified entitiesGeneral web applications, public APIs, mobile backends
GraphQLHTTP using JSONQuery-driven: Single endpoint, client requests exact fields neededComplex social graphs, highly connected mobile apps
gRPCHTTP/2 using Protocol BuffersContract-first binary RPC: Extreme throughput and bi-directional streamingHigh-performance microservice-to-microservice communication

4.2 REST principles and design, RESTful APIs

Representational State Transfer (REST) is an architectural style for distributed hypermedia systems, formulated by Roy Fielding in his 2000 doctoral dissertation. Rather than defining a strict technical standard, REST outlines six foundational architectural constraints.

The Six Guiding Architectural Constraints of REST

  1. Client-Server Architecture: Enforces separation of concerns. The client manages user interface state and user interaction; the server manages data storage, security, and business rules. Both layers evolve independently across different hardware and programming languages.
  2. Statelessness: Every HTTP request from client to server must contain all information necessary to understand and process the request (including authentication credentials, query parameters, and resource identifiers). The server stores no conversational session state regarding the client. Statelessness simplifies server scaling, as any server instance in a cluster can handle any incoming request.
  3. Cacheability: To conserve network bandwidth and minimize server latency, response messages must explicitly declare themselves as cacheable or non-cacheable using standard HTTP headers (Cache-Control: max-age=3600, ETag, Last-Modified). Clients and intermediate reverse proxies can reuse fresh cached representations.
  4. Layered System: A client cannot determine whether it is connected directly to the end application server or to an intermediate proxy, load balancer, API gateway, or security firewall. Layered intermediaries can enforce caching, encryption termination, and rate limiting transparently.
  5. Uniform Interface: The central hallmark that differentiates REST from other network architectures. The uniform interface comprises four sub-constraints:
    • Identification of Resources: Individual resources are identified in requests using standard Uniform Resource Identifiers (e.g., /api/v1/students/1042).
    • Manipulation of Resources Through Representations: Clients manipulate resources by transmitting representations (JSON, XML) paired with HTTP verbs (GET, POST, PUT, DELETE).
    • Self-Descriptive Messages: Every message contains enough metadata for the receiver to process it, including MIME media types (Content-Type: application/json).
    • Hypermedia As The Engine Of Application State (HATEOAS): The server dynamically delivers hyperlinks within response payloads, guiding the client on available next actions without requiring hardcoded client-side URLs.
  6. Code on Demand (Optional): Servers can temporarily extend client functionality by transmitting executable code (such as JavaScript scripts or compiled applets).

RESTful URI Design Conventions

High-quality RESTful API design adheres to clean, predictable resource-oriented URI naming conventions:

Standard RESTful Endpoint Design Guidelines
HTTP VerbEndpoint PathIdempotent?Safe?Action & Expected HTTP Status
GET/api/v1/coursesYesYesRetrieve paginated collection of courses (200 OK)
POST/api/v1/coursesNoNoCreate a new course entity (201 Created + Location header)
GET/api/v1/courses/{id}YesYesRetrieve single course representation (200 OK or 404 Not Found)
PUT/api/v1/courses/{id}YesNoCompletely replace course record (200 OK or 204 No Content)
PATCH/api/v1/courses/{id}NoNoPartially update specific course fields (200 OK)
DELETE/api/v1/courses/{id}YesNoRemove course entity permanently (204 No Content)
GET/api/v1/courses/{id}/studentsYesYesRetrieve nested sub-resource collection (200 OK)

Key Design Rules:

The Richardson Maturity Model

Developed by Leonard Richardson, this model grades the maturity of a web service based on its compliance with RESTful principles:

The Richardson Maturity Model (Levels 0 through 3)Text
  [ Level 3: Hypermedia Controls ] -> HATEOAS: Responses include clickable dynamic link relations
                 ^
  [ Level 2: HTTP Verbs ] ---------> Leverages GET, POST, PUT, DELETE with appropriate HTTP status codes
                 ^
  [ Level 1: Resources ] ----------> Individual resource URIs (/students/10, /courses/5) instead of single endpoint
                 ^
  [ Level 0: The Swamp of POX ] ---> Single URI (/api/service), single verb (POST), arbitrary XML/JSON payloads
  1. Level 0 (The Swamp of POX): Uses HTTP strictly as a transport tunnel. All requests are dispatched to a single endpoint (e.g., /endpoint) using a single HTTP method (POST), packaging operations in custom payloads (e.g., standard SOAP or XML-RPC).
  2. Level 1 (Resources): Introduces multiple discrete URIs to identify distinct resources (e.g., /student/1, /student/2), but still relies on a single verb (typically POST) for all actions.
  3. Level 2 (HTTP Verbs): Leverages the full spectrum of standardized HTTP methods (GET for retrieval, DELETE for removal, POST for creation) paired with correct semantic status codes (200, 201, 400, 404).
  4. Level 3 (Hypermedia Controls / HATEOAS): The highest tier of REST compliance. Representations return not only resource state, but also hypermedia links (_links) declaring what related actions the client can perform next.

4.3 JSON versus XML data exchange

Data exchange formats serialize in-memory data structures into structured textual byte streams for transmission across network boundaries. JSON and XML represent the two dominant data exchange formats in web engineering.

JSON (JavaScript Object Notation)

Standardized under RFC 8259, JSON is a lightweight, text-based data interchange format derived from the object literals of JavaScript. It supports two structural collections:

Supported scalar types: string, number, boolean, null.

XML (eXtensible Markup Language)

Standardized by the W3C, XML is a tree-structured, tag-based markup language derived from SGML. It encloses data within opening and closing tags, supporting attributes, nested elements, processing instructions, and comments:

HTML
<?xml version="1.0" encoding="UTF-8"?>
<course code="ENCT 302">
  <title>Web Application Programming</title>
  <hours>45</hours>
  <marks>80</marks>
  <instructors>
    <instructor id="101">Faculty of Computer Engineering</instructor>
  </instructors>
</course>

Equivalent JSON representation:

Text
{
  "code": "ENCT 302",
  "title": "Web Application Programming",
  "hours": 45,
  "marks": 80,
  "instructors": [
    { "id": 101, "name": "Faculty of Computer Engineering" }
  ]
}
Technical Comparison: JSON vs. XML
Technical AttributeJSON (JavaScript Object Notation)XML (eXtensible Markup Language)
Syntax Verbosity & OverheadExtremely compact; concise brackets and key quotes minimize payload bytesVerbose; repeating opening and closing tag names inflates byte size
Parsing Speed & EfficiencyFast native parser in browsers (JSON.parse); low CPU and memory overheadRequires complex tree parsers (DOM parser) or stream parsers (SAX); higher CPU cost
Data Types SupportedNative typed scalars: string, number, boolean, array, object, nullUntyped text strings; all values and attributes are character data
Schema ValidationJSON Schema (declarative, flexible, gaining widespread adoption)XML Schema Definition (XSD), DTD (mature, rigorous, highly comprehensive)
Metadata & NamespacesNo native namespace support; metadata must be embedded as normal object propertiesNative support for XML Namespaces (xmlns), attributes, and CDATA sections
Transformation ToolingHandled via programming language mapping or JMESPath/jqStandardized transformation languages: XSLT, XPath, XQuery
Modern Web DominanceUniversal standard for modern RESTful APIs, Single Page Apps, NoSQL (MongoDB)Enterprise banking, SOAP services, document markup (SVG, MathML, Office docs)

4.4 Data validation and serialization

Web APIs require strict validation and serialization barriers at the network perimeter to convert external unstructured payloads into verified internal domain entities.

Serialization and Deserialization Concepts

Definition

Serialization and Deserialization

Data Validation at the API Boundary

Because Web APIs accept data from untrusted public networks, all incoming payloads must undergo rigorous multi-stage validation:

  1. Type & Structural Validation: Enforcing correct scalar types (e.g., verifying semester is an integer between 1 and 8, not a string).
  2. Schema & Constraint Validation: Ensuring mandatory fields are present, string lengths conform to database column limits, and email formats match validation patterns.
  3. Business Rule Validation: Enforcing application-specific domain logic (e.g., verifying that a student cannot register for an elective course if prerequisite requirements are unfulfilled).
  4. Sanitization: Stripping control characters and malicious markup to prevent SQL injection and cross-site scripting (XSS).

Standardized Error Reporting (RFC 7807)

When validation fails, professional RESTful APIs emit standardized error payloads conforming to RFC 7807 (Problem Details for HTTP APIs), utilizing the media type application/problem+json:

Text
{
  "type": "https://api.tu.edu.np/errors/validation-failed",
  "title": "Invalid Student Registration Payload",
  "status": 422,
  "detail": "One or more fields in the submitted registration request failed validation.",
  "instance": "/api/v1/students/registration/txn-89102",
  "invalid_params": [
    {
      "name": "email",
      "reason": "Email address must belong to the @pcampus.edu.np domain."
    },
    {
      "name": "semester",
      "reason": "Semester value must be an integer between 1 and 8."
    }
  ]
}

4.5 Microservices

As enterprise software systems expand in organizational complexity and transaction volume, their underlying architectures frequently transition from monolithic codebases to distributed microservice clusters.

Monolithic vs. Microservices Architecture

AspectMonolithic ArchitectureMicroservices Architecture
Codebase & DeploymentSingle unified codebase deployed as a single large executable archive (e.g., one .war or Django repository)Suite of small, autonomous, independently deployable services organized around business domains
Database ArchitectureSingle centralized shared database containing all application tablesDatabase-per-service: Each microservice strictly owns and manages its private database
Scaling CapabilityCoarse-grained: Entire monolith must be scaled horizontally, even if only one module requires more CPUFine-grained: Scale individual bottleneck services independently based on demand
Fault IsolationPoor: A memory leak or fatal crash in one module brings down the entire application processStrong: Failure of one microservice (e.g., notifications) does not crash critical core services (e.g., payments)
Technology DiversityHomogeneous: Entire codebase is locked into one programming language and frameworkHeterogeneous: Teams select optimal languages per service (e.g., Python for ML, Go for APIs, Java for banking)
Operational ComplexityLow: Simple local debugging, straightforward single-server deploymentsHigh: Requires automated CI/CD, container orchestration (Docker/Kubernetes), distributed tracing, and service meshes

Core Microservices Design Patterns

To coordinate distributed microservices reliably, architectures employ standardized enterprise design patterns:

1. API Gateway Pattern

Instead of client browsers communicating directly with dozens of individual internal microservices, all incoming external traffic terminates at an API Gateway (e.g., Kong, Nginx, Envoy, AWS API Gateway):

2. Circuit Breaker Pattern

In a distributed microservice network, cascading failures occur when Service A synchronously calls Service B, which is unresponsive or experiencing high latency. As incoming requests accumulate, Service A exhausts its thread pool, crashing itself and triggering a domino collapse across the entire cluster.

Definition

Circuit Breaker States

The Circuit Breaker pattern monitors calls to downstream remote services and wraps them in a state machine:

  1. Closed State (Normal): Requests pass freely to the downstream service. The circuit breaker counts recent failures. If the failure rate remains below a threshold, it stays Closed.
  2. Open State (Tripped): When the failure rate exceeds a configured threshold (e.g., 50% errors), the breaker trips to Open. All incoming requests fail immediately (or execute a fallback routine) without attempting network calls to the downstream service, granting the struggling service time to recover.
  3. Half-Open State (Trial Recovery): After a reset timeout period (e.g., 30 seconds), the breaker transitions to Half-Open. A limited number of trial requests are permitted through. If they succeed, the breaker resets to Closed; if any trial request fails, it immediately reverts to Open.

3. Distributed Transactions and the Saga Pattern

Because microservices forbid cross-service SQL JOINs or distributed two-phase commit (2PC) locks that impair availability, distributed state changes across services rely on the Saga Pattern: A sequence of local transactions where each local transaction updates data within a single service and publishes an event or message. If a downstream step fails, the Saga executes compensating transactions in reverse order to roll back prior changes and preserve eventual consistency.


Worked Examples

Example

Payload Bandwidth Consumption: JSON versus XML

A university examination API serves a list of 1,000 enrolled students. An analysis of the data structures reveals:

  1. Calculate the total uncompressed network payload size in kilobytes (KB, where 1 KB = 1024 bytes) for transmitting the 1,000 student records under both XML and JSON formats.
  2. Calculate the exact byte bandwidth savings achieved by adopting JSON over XML.
  3. Calculate the percentage reduction in payload size achieved by switching from XML to JSON.

Calculate Total Payload Sizes in Bytes and Kilobytes: Number of student records = 1,000.

For XML: Total XML bytes = 1,000 * 280 bytes = 280,000 bytes. In Kilobytes: 280,000 / 1024 = 273.4375 KB (approximately 273.44 KB).

For JSON: Total JSON bytes = 1,000 * 130 bytes = 130,000 bytes. In Kilobytes: 130,000 / 1024 = 126.953125 KB (approximately 126.95 KB).

Calculate Exact Bandwidth Savings in Bytes: Bandwidth Savings = Total XML Bytes - Total JSON Bytes Bandwidth Savings = 280,000 - 130,000 = 150,000 bytes. In Kilobytes: 150,000 / 1024 = 146.484375 KB.

Calculate Percentage Reduction: Percentage Reduction = (Bandwidth Savings / Total XML Bytes) * 100 Percentage Reduction = (150,000 / 280,000) * 100 Percentage Reduction = 15 / 28 * 100 = 53.5714% (approximately 53.57%).

Answer:
  1. XML requires 280,000 bytes (273.44 KB); JSON requires 130,000 bytes (126.95 KB).
  2. Adopting JSON yields an absolute saving of 150,000 bytes (146.48 KB) per transmission.
  3. JSON delivers a 53.57% reduction in network payload bandwidth compared to XML.
Example

Designing a RESTful HATEOAS API Response (Richardson Level 3)

Design a Richardson Maturity Model Level 3 (HATEOAS) JSON response payload for an enrolled student course resource: GET /api/v1/students/PUL078BCT001/courses/ENCT302

The student is currently enrolled with tuition fees paid. The response must include:

  1. Core resource data (student roll, course code, grade status, credits).
  2. Standard hypermedia link relations (_links) pointing to the resource itself, the parent student profile, syllabus documentation, and allowable state transitions (such as dropping the course or viewing attendance records).

Construct the HATEOAS JSON Payload Structure: Using the standardized HAL (Hypertext Application Language) JSON convention, dynamic navigational links are enclosed under the reserved _links property:

Text
{
  "student_roll": "PUL078BCT001",
  "course_code": "ENCT 302",
  "course_title": "Web Application Programming",
  "semester": 5,
  "credit_hours": 3,
  "enrollment_status": "CONFIRMED",
  "attendance_percentage": 92.5,
  "_links": {
    "self": {
      "href": "/api/v1/students/PUL078BCT001/courses/ENCT302",
      "method": "GET"
    },
    "student": {
      "href": "/api/v1/students/PUL078BCT001",
      "method": "GET"
    },
    "syllabus": {
      "href": "/api/v1/courses/ENCT302/syllabus",
      "method": "GET"
    },
    "attendance_records": {
      "href": "/api/v1/students/PUL078BCT001/courses/ENCT302/attendance",
      "method": "GET"
    },
    "drop_course": {
      "href": "/api/v1/students/PUL078BCT001/courses/ENCT302/drop",
      "method": "POST"
    }
  }
}

Explain HATEOAS Benefits: By including hypermedia controls, the client does not need to construct or hardcode internal API endpoint URLs. If the business rules change (for example, if the registration deadline passes and dropping the course is no longer permitted), the backend simply omits the drop_course link from the _links object, and the client UI dynamically disables the "Drop Course" button automatically.

Answer:

The JSON response combines domain state with HAL-compliant _links (self, student, syllabus, attendance_records, and state transition drop_course). This achieves Richardson Maturity Model Level 3, allowing client applications to discover all available actions dynamically.

Example

API Gateway Token Bucket Rate Limiter Calculations

An API Gateway protects a campus registration service using the Token Bucket rate-limiting algorithm. The configuration specifies:

At time t = 0, the bucket contains 500 tokens.

  1. If no requests arrive for 10 seconds, calculate the token count in the bucket at t = 10 seconds.
  2. At t = 10 seconds, a burst of 800 concurrent requests arrives instantaneously. Determine how many requests are accepted and how many tokens remain in the bucket.
  3. If no further requests arrive for the next 4 seconds, calculate the final token balance at t = 14 seconds.

Calculate Refill at t = 10 seconds: Tokens at t = 0: 500 tokens. Elapsed time = 10 seconds. Tokens generated = 10 seconds * 50 tokens/sec = 500 tokens. Potential total tokens = 500 + 500 = 1,000 tokens. Because the maximum bucket capacity is 1,000 tokens, the bucket fills completely to its ceiling: Tokens at t = 10 = 1,000 tokens.

Process the Instantaneous Burst of 800 Requests: Available tokens in bucket = 1,000. Burst request volume = 800 requests. Because 800 <= 1,000:

  • All 800 requests are accepted and processed with HTTP 200 OK.
  • Remaining tokens = 1,000 - 800 = 200 tokens.

Calculate Balance at t = 14 seconds: Time elapsed since burst = 4 seconds. Refill generated = 4 seconds * 50 tokens/sec = 200 tokens. New token balance = 200 (remaining) + 200 (refilled) = 400 tokens. Because 400 <= 1,000 (maximum capacity), the final token balance is exactly 400 tokens.

Answer:
  1. At t = 10 seconds, the bucket reaches maximum capacity with 1,000 tokens.
  2. All 800 burst requests are accepted; 200 tokens remain in the bucket.
  3. At t = 14 seconds, after 4 seconds of refilling, the final balance is 400 tokens.

Exercises

Practice Exercises — Web Services and APIs

Question 1

List and explain the six architectural constraints of the REST architectural style defined by Roy Fielding. Explain why violating statelessness compromises horizontal scaling.

The Six Architectural Constraints of REST:

  1. Client-Server: Decouples user interface concerns from data storage and business rules.
  2. Stateless: Every incoming request must contain all contextual information required to fulfill it; the server retains zero client conversational session state between requests.
  3. Cacheable: Responses must explicitly define their caching properties (Cache-Control) to permit client and proxy caching.
  4. Layered System: The architecture can incorporate intermediate proxies, load balancers, and security gateways without client awareness.
  5. Uniform Interface: Guarantees standardized resource identification via URIs, manipulation via representations, self-descriptive messages, and hypermedia controls (HATEOAS).
  6. Code on Demand (Optional): Servers may temporarily extend client capabilities by transmitting executable scripts.

Why Violating Statelessness Compromises Horizontal Scaling: When an application is stateful (storing client session state in server memory), an incoming request from a user can only be processed by the specific server node holding that user's session data. This forces the load balancer to configure sticky sessions (session affinity). If that specific server instance crashes, the user's active session is lost. If traffic surges on that node, the cluster cannot freely distribute requests across other underutilized nodes. In contrast, in a purely stateless RESTful system, any incoming request can be routed to any available worker node, enabling seamless horizontal auto-scaling.

Answer:

REST enforces: Client-Server, Statelessness, Cacheability, Layered System, Uniform Interface, and optional Code on Demand. Violating statelessness requires sticky sessions, creating single-point-of-failure bottlenecks that prevent load balancers from distributing requests evenly across server clusters.

Question 2

Describe the Richardson Maturity Model for REST APIs. Detail the architectural characteristics of Levels 0, 1, 2, and 3 with concrete API endpoint examples.

The Four Levels of the Richardson Maturity Model:

  • Level 0 (The Swamp of POX): Uses HTTP strictly as a transport tunnel. Employs a single URI and single HTTP verb (usually POST) for all operations. Example: POST /api/service with an XML payload <action>getCourse</action><id>101</id>.
  • Level 1 (Resources): Introduces individual, addressable resource URIs for different entities, but still relies on a single verb (typically POST) for all operations. Example: POST /api/courses/101 to fetch course data, and POST /api/courses/101/delete to delete it.
  • Level 2 (HTTP Verbs): Employs standard HTTP verbs (GET to read, POST to create, PUT to replace, DELETE to remove) paired with semantic status codes (200 OK, 201 Created, 204 No Content, 404 Not Found). Example: GET /api/v1/courses/101 and DELETE /api/v1/courses/101.
  • Level 3 (Hypermedia Controls / HATEOAS): Responses return both resource state and navigational hypermedia links (_links) declaring all valid next actions. Example: A GET /orders/5 response includes a cancel_order link only while the order is in pending status.
Answer:

The Richardson Maturity Model ranks REST compliance from Level 0 (single endpoint POX tunnel), Level 1 (individual resource URIs), Level 2 (standard HTTP verbs and status codes), to Level 3 (HATEOAS hypermedia navigation links within payloads).

Question 3

Compare JSON and XML as data exchange formats for web services. Discuss their differences in payload overhead, parsing performance, schema validation, and appropriateness for mobile web applications.

Comparison of JSON and XML:

  • Payload Overhead: XML is verbose; repeating opening and closing tags (e.g., <studentName>...</studentName>) inflates payload sizes. JSON uses concise keys and brackets, reducing uncompressed byte footprint by 40% to 60%.
  • Parsing Performance: JSON maps directly to native JavaScript data structures (JSON.parse()) and compiles rapidly in browser runtimes. XML requires heavier hierarchical DOM or SAX parsers, consuming significantly higher CPU and RAM resources.
  • Schema Validation: XML offers highly mature, standardized schema validation via XML Schema Definition (XSD) and namespaces. JSON uses JSON Schema, which is simpler and declarative, though historically less standardized in enterprise environments.
  • Mobile Web Suitability: JSON is overwhelmingly preferred for mobile web applications due to reduced bandwidth consumption, lower battery usage during parsing, and straightforward integration with mobile JSON deserializers (such as Gson, Moshi, Swift Codable).
Answer:

JSON is compact, natively parsed, lightweight, and ideal for bandwidth-constrained mobile web applications. XML provides robust schema validation (XSD) and namespaces but suffers from verbose markup and computationally expensive parsing.

Question 4

Differentiate between Monolithic Architecture and Microservices Architecture. What are the primary trade-offs regarding database management, deployment velocity, and distributed debugging?

Architectural Differences:

  • Monolith: An all-in-one software package where UI, business logic, and database access routines are bundled into a single unified binary and share a single database.
  • Microservices: A distributed system of autonomous, domain-focused services communicating over lightweight network protocols (HTTP/REST or gRPC), each maintaining its own private database.

Trade-Offs across Core Dimensions:

  1. Database Management: Monoliths provide straightforward ACID transactions and simple SQL JOINs across all tables. Microservices enforce the Database-per-Service pattern; distributed transactions require eventual consistency models (such as the Saga pattern) and eliminate cross-service relational joins.
  2. Deployment Velocity: In a monolith, changing a single line of code requires rebuilding and redeploying the entire multi-gigabyte application. Microservices allow independent teams to deploy individual services multiple times a day without impacting other services.
  3. Distributed Debugging: Monoliths provide straightforward local debugging with a single unified stack trace. Microservices introduce complex distributed debugging challenges requiring correlation IDs, distributed tracing systems (Jaeger, Zipkin), and centralized log aggregators (ELK stack).
Answer:

Monoliths combine all modules and a single database into one deployable unit, providing simple ACID transactions but slow deployment velocity. Microservices partition domains into independent deployables with private databases, achieving high deployment velocity and fault isolation at the expense of distributed transaction and debugging complexity.

Question 5

Explain the API Gateway Pattern and the Circuit Breaker Pattern in microservices architectures. Describe the three operating states of a Circuit Breaker.

The API Gateway Pattern: An API Gateway acts as a single centralized reverse-proxy entry point for all external client traffic. It handles:

  • Request routing and protocol translation (e.g., HTTP/REST to gRPC).
  • Centralized cross-cutting concerns: authentication, SSL termination, global rate limiting, and CORS.
  • Response aggregation: Composes data from multiple internal microservices into a single consolidated payload for mobile clients.

The Circuit Breaker Pattern and Its Three Operating States: Prevents cascading failures across a distributed microservices network when a downstream dependency experiences high latency or outages:

  1. Closed State (Normal): Requests pass freely to the downstream service. The circuit breaker tracks recent failure rates. If failure count remains below the threshold, it stays Closed.
  2. Open State (Tripped): When error rates exceed the threshold (e.g., 50% failures), the breaker trips to Open. All subsequent requests fail immediately (returning fallback data) without dispatching network calls, preventing server thread pool exhaustion.
  3. Half-Open State (Trial Recovery): After a cooldown period, the breaker allows a small sample of test requests through. If they succeed, the breaker resets to Closed; if any test request fails, it immediately returns to Open.
Answer:

The API Gateway acts as a single entry point handling routing, authentication, and request aggregation. The Circuit Breaker protects systems from cascading failures using three states: Closed (normal execution), Open (failing immediately when errors exceed threshold), and Half-Open (permitting trial requests to test recovery).

← Server-Side Web Programming (part 2: 3.6–3.10)Web Application Security →