Search Sreeni's Insights

Filter by content type
technical September 15, 2016 7 min read

Fine-grained vs coarse-grained APIs - avoiding chatty APIs

Fine-grained and coarse-grained APIs compared through response shape, client composition, network calls, latency, business views and the cost of chatty requests.

Share:

Fine-grained vs coarse-grained APIs - avoiding chatty APIs

An API can be perfectly resource-oriented and still create a poor client experience when one screen is making many small requests. The problem is not that a fine-grained endpoint is always wrong. The network boundary is changing the cost of a call. In the previous article, we discussed the API Gateway as a front door for clients and services. In this article, we are going to compare fine-grained and coarse-grained API shapes using a fund details page.

TL;DR Summary

  • Fine-grained APIs expose small resource operations and can be reusable.
  • Coarse-grained APIs return the data needed by a business use case in fewer calls.
  • Chatty APIs add latency, failure points and client complexity.
  • Coarse-grained endpoints can become too large or too coupled when designed without a use case.
  • A response should be shaped around consumer needs while preserving domain ownership.
  • Request count, payload size and end-to-end latency should be measured.
  • An API Gateway or backend-for-frontend can compose data without making every client do it.

Challenges

The screen is calling for every field

A fund details page may call the fund endpoint, price endpoint, documents endpoint, ratings endpoint and managers endpoint one after another. Each call is small, but the total time is including network latency and independent failure. Users are experiencing the sum rather than the elegance of each resource.

One giant response is created

The answer to chatty calls is not one response containing every table in the database. A coarse response serving all clients is difficult to cache, version and secure. It may also carry data which the user never asked to see.

Reuse is confused with client coupling

A reusable resource endpoint is valuable, but forcing every client to compose it in the same way is moving composition work to each client. Stable business views are useful when several consumers have the same need, while special views should remain explicit.

What are fine-grained and coarse-grained APIs?

A fine-grained API exposes small operations around resources, while a coarse-grained API combines the data and actions needed by a larger consumer use case.

In simple terms, five small requests are fine-grained, and one request for the fund page view is coarse-grained. The right size depends on the consumer, latency, reuse and maintainability.

An everyday analogy is shopping for a meal. Fine-grained calls are five trips to five small shops. Each shop is focused and reusable, but the travel time is adding up. A coarse-grained market is giving more items in one trip, but it is wasteful if we are buying only one item.

Why API granularity is important?

Network calls are introducing latency, connection limits, retries and partial failure. A good API is not measured only by how pure its resource nouns are; it is also measured by whether consumers can complete their business action reliably.

The following diagram depicts the same client need in two ways:

Fine-grained versus coarse-grained API calls
Fine-grained versus coarse-grained API calls

The fine-grained panel shows five GET requests for Fund 1: the fund, prices, documents, ratings and managers. The coarse-grained panel shows one request using include=prices,documents. The diagram is not saying that every endpoint should be combined. It is showing where the consumer use case is creating a better boundary.

Designing a coarse-grained response

For a fund summary screen, the request can be:

GET /funds/1?include=prices,documents HTTP/1.1
Accept: application/json

The response should be bounded and explicit:

{
  "id": 1,
  "name": "Global Equity Fund",
  "currency": "GBP",
  "latestPrice": {
    "value": 10.50,
    "asOf": "2016-06-30"
  },
  "documents": [
    { "id": "factsheet-2016-06", "title": "Factsheet" }
  ]
}

The API does not return manager history, every price point or private documents merely because the database can join them. The include list is validated against an allowed set. A client asking for an unsupported include receives a useful 400 response instead of silently receiving a huge payload.

Avoiding hidden coupling

The coarse response should be owned by the team which understands the consumer view. It can be implemented in a Gateway, a backend-for-frontend or a read model. The endpoint should not be joining databases which belong to independent services. It can call Pricing and Documents with bounded timeouts and return an explicit partial result only when the product has agreed what partial means.

Measuring the change

Before changing the API, record the number of calls, total page latency, payload size and error count. After the change, compare the same values. A single call with a 5 MB response is not necessarily better than three small calls. The metric depends on the user journey.

Trade-offs

ApproachProsCons
Fine-grained+ Reusable and focused resources<br>+ Smaller response contracts− More network calls<br>− Client composition and latency
Coarse-grained+ Fewer calls and simpler clients<br>+ Fits a business view− Larger contract and payload<br>− Can become coupled or difficult to cache

In our case, we are keeping resource APIs focused and adding a coarse view for a measured fund page need. We are not combining every related object. A mobile client can receive a summary response, while a reporting client can use separate endpoints suited to its own query.

Pagination, errors and caching

A coarse response is still bounded. The fund summary can contain the latest price and three public document links, but it should not include every historical price or every news article. Historical prices are paged with a continuation token, and a document list returns a count and links rather than the complete document body.

Partial failure is designed explicitly. If Pricing is unavailable, the API can return a dependency error for the complete summary, or the product can approve a response which shows the fund name and marks the price unavailable. Returning 0.00 is never an acceptable fallback for a financial value because the client will read it as a real price.

The cache key includes the fund id and allowed include set. A response for include=prices is not returned for a request which asks for include=prices,documents. ETag and Cache-Control are selected according to whether the view is public and how quickly a price can change.

The contract is tested with a consumer-driven test. The mobile client checks the fields it needs, while the API test checks that a removal or rename is versioned. The test prevents a coarse endpoint from silently becoming a database projection which every client depends on.

The request is also considering network behaviour. A mobile client on a slower connection benefits from one bounded request, but a very large document response is wasting bandwidth. The coarse view is returning summary metadata and links, while the document download is remaining a separate request which can use a CDN or a resumable transfer.

The API is selecting parallel calls when the dependencies are independent. Pricing and public document metadata can be requested together, while a dependent call is waiting only when its input is known. Each call is having its own timeout, and the endpoint is recording which dependency caused the delay.

A versioned view is useful when a client cannot move immediately. GET /funds/1/summary-v1 can remain stable while summary-v2 adds a new price format. The team is not changing the meaning of latestPrice in place and expecting old mobile clients to understand it. This is preserving a healthy contract while the backend is changing.

The API design also considers access control. A coarse view for a public fund page is not automatically safe for a partner report containing restricted holdings. The view is authorised as one business operation, and each included resource is reviewed for its data classification.

The response is designed with names which are meaningful to the consumer. latestPrice is a business value, while priceTableRow17 exposes a database shape. This small discipline makes later storage changes less visible to the client.

Must Do and Don’ts

  • Must Do: Design the response from a named user journey, otherwise the coarse endpoint will become a database dump.
  • Must Do: Set a maximum include set and payload size, because an unrestricted query becomes a denial-of-service risk.
  • Must Do: Measure request count and total latency before and after, so “less chatty” has evidence.
  • Must Do: Version a response when its meaning changes, because clients are not upgrading together.
  • Don’t: force a single coarse response on every consumer, otherwise unused data and coupling will grow.
  • Don’t: make a client call five services serially when one owned composition boundary is available, because latency will be multiplied.

Wrap up

In this article, we have looked at fine-grained resources, coarse-grained business views, JSON response design and the cost of chatty requests. In our case, the API is shaped around the fund page rather than around every database table. I appreciate your time and efforts to read this article. In the next article, I will walk you through idempotency in REST APIs and why DELETE twice is still gone.

Related Posts