SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
  • Service Discovery
  • API Gateway Pattern
  • Backend for Frontend (BFF)
  • Sidecar Pattern
  • Circuit Breaker
  • Bulkhead
  • Strangler Fig
  • Service Mesh
  • Database per Service
  • Timeouts and Deadlines
  • API Composition
  • Anti-Corruption Layer
  • Ambassador Pattern
  • Idempotent Consumer and Inbox Pattern
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Architecture/Microservices Patterns

API Composition

Build one answer by calling several services and combining the results in one place.

⏱ 12 min readIntermediateInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

API composition means that when one answer needs data from several services, one piece of code (the composer) calls them all and joins the results in memory.

  • In a microservices system each service owns its own data, so you cannot write one SQL join across them.
  • The composer is often an API gateway, a backend for frontend, or a small aggregator service.
  • Calls that do not depend on each other go out in parallel, so the page takes as long as the slowest call, not the sum.

02Concept: What is it?

Think about a product page in a shop. It shows the product details, the price, the reviews and a list of recommended items. In a microservices system, each of these four things lives in its own service, with its own database. There is no single table to JOIN.

So someone has to ask each service and put the answers together. That is the API composition pattern. The composer receives one request from the client, sends several requests to the services behind it, waits for the answers, builds one combined response, and sends it back.

The composer does no business work of its own. It is a coordinator: it knows which services to call, in which order, what to do when one is slow or down, and how to merge the pieces into the shape the client wants.

One request, four calls, one answer
πŸ“±ClientGET /product-page
→↓1 request
🧩Composerfan out, then join
→↓4 calls
πŸ“¦Product
πŸ’²Price
⭐Reviews
🎯Recs
The client makes one call. The composer fans out to the services and joins what comes back.
🧠It is a join done in code
A database joins tables inside one engine, with indexes and a query planner. The composer joins in memory, after the network calls. That is fine for a few small answers, and slow for big ones.

03Real-Life Example

🍡The Travel Agent with Four Phone Calls
You ask a travel agent, "What will my trip to Lisbon cost, and is it any good?" The agent does not know everything. They phone the airline for flight prices, the hotel for rooms, a review site for ratings, and a tour company for activities. If the agent phones all four at the same time, you wait only as long as the slowest one. If they phone one after another, you wait for all four, one by one. If the review site does not pick up, a good agent says, "Here are your flights and hotel. The reviews are not available right now." A bad agent says, "Sorry, I cannot help at all."
Travel agent
API composition
The travel agent
The composer (gateway, BFF or aggregator)
Airline, hotel, review site, tour company
The services, each with its own data
Phoning all four at once
Parallel calls: time is the slowest call
Phoning one after another
Sequential calls: time is the sum
Putting the answers into one summary
Joining the results in memory
The review site is busy
A timeout or failure in one service
"Reviews not available right now"
A partial response with a fallback
Parallel and sequential calls
Parallel (independent)
Product30 ms
Price25 ms
Reviews60 ms
Total is about 60 ms (the slowest)
Sequential (one by one)
Product30 ms
Price25 ms
Reviews60 ms
Total is about 115 ms (the sum)
Overlapping in time One after another

04Why Do We Need It?

πŸ—„οΈData is split on purpose
With a database per service, no single query can see all the data. Something must collect it.
πŸ“±Simple for clients
A phone makes one call instead of four. Less battery, fewer round trips, simpler client code.
🧰Easy to start
No new database and no event pipeline. A little code that calls services is enough.
πŸ”ŒServices stay independent
Each service keeps its own simple API. Only the composer knows how to combine them.
πŸ›ŸControl over failure
One place decides about timeouts, fallbacks and partial answers.
πŸ”’Hides the inside
Clients do not learn how many services you have, or what they are called.
If the data lives in many services, someone has to ask them all. API composition is the simplest way to do it.

05Where Do We Use It?

πŸšͺInside an API gateway
The gateway offers one endpoint and calls several services behind it.
πŸ“²Backend for frontend
A BFF per client composes exactly what that screen needs.
🧩Aggregator services
A small service whose only job is to combine data (order details, account overview).
πŸ•ΈοΈGraphQL servers
A GraphQL server resolves each field from a different service, so it composes by design.
πŸ›’Shop pages
Product, price, stock, reviews and offers on one page.
🏦Dashboards
An account overview with balance, cards and recent activity from different systems.

06Types / Parts / How It Works

Who plays the composer?

ComposerWhat it isGood for
API gatewayThe edge door of the system also combines a few callsSimple joins that every client needs
Backend for frontendOne backend per client type, shaped for its screensMobile and web needing different data
Aggregator serviceA normal service whose job is to combine othersReusable composition, shared by several clients
GraphQL layerResolvers fetch each field from the right serviceClients that choose their own fields

Order of the calls

StyleHow it worksTotal timeUse when
ParallelSend all calls at once, then wait for allAbout the slowest callThe calls do not need each other's answers
SequentialCall one, use its answer for the nextThe sum of the callsCall B needs data from call A
MixedSome in parallel, some after a first stepIn betweenMost real pages: fetch the product first, then price and stock for it

Composition or a read model?

Two ways to answer a question that spans services
API composition
🧩Composercalls services when asked
↓live calls
πŸ“¦A
⭐B
CQRS read model
πŸ“–Read storealready joined
↑events keep it updated
πŸ“¦A
⭐B
Composition asks at read time. A read model prepares the answer in advance.
VisualizerA product page that needs four servicesSwitch between parallel and one-after-another calls, slow down a service, then switch one off. Compare failing the whole page with a partial page, and watch the page availability.
How are the calls made?
If a part fails
πŸ“±Clientone request
→↓GET /product-page
🧩Composercalls all at once
↓
πŸ“¦Product40 ms
πŸ’²Price30 ms
⭐Reviews90 ms
🎯Recommendations150 ms
Product
40 ms
Price
30 ms
Reviews
90 ms
Recommendations
150 ms
Availability of each service on its own
Page time
155 ms
slowest call + composer
Page works?
Yes
all parts present
Page availability
99.601%
4 services must work
Downtime a month
173 min
one service alone: 43 min
All answers arrived. In parallel the composer waits only for the slowest call, so the total is about 155 ms, not the sum of all four.

A simplified model with made-up numbers (illustrative): a service that is down is noticed after 300 ms, optional parts get 120 ms in partial mode, and the composer itself costs 5 ms. In the fail-all mode the composer waits for every reply before it decides. Availability is the exact product of the services that must work: availability to the power of 4, assuming independent failures, over a 30-day month. Real systems also share failures (the same network, the same data centre).

07How to Use It / Steps / Implementation

Building a composer

  1. 1
    List what the answer needs
    Write down every field of the response and which service owns it.
  2. 2
    Find the dependencies
    Which calls need an earlier answer? Put the rest in parallel. This single choice often cuts the time in half.
  3. 3
    Set a timeout on every call
    Never wait forever. Give each call a limit, and pass the remaining time down (a deadline).
  4. 4
    Decide what is essential
    A product page cannot work without the product. It can work without reviews. Mark each part as required or optional.
  5. 5
    Plan the fallback for optional parts
    Return a cached copy, an empty list, or a flag such as reviews unavailable. Do not fail the page for it.
  6. 6
    Protect the services
    Use a circuit breaker and a limit on how many calls a single request may start (fan-out).
  7. 7
    Cache what is stable
    Product details change rarely. Do not call the service for them on every page view.
  8. 8
    Measure each call
    Trace one request through all of its calls, so you can see which service makes the page slow.
πŸ’‘Use a deadline, not just timeouts
If the client gave you 500 ms in total, tell each service how much of that time is left. A call that starts late then gets a smaller limit, and the whole request cannot run long.
⚠️Keep it a coordinator
If the composer starts holding business rules (discounts, tax, eligibility), it grows into a hidden monolith. Keep the rules in the services and only combine in the composer.

08Key Terms to Know

TermMeaning in easy words
ComposerThe code that calls several services and combines their answers (also called an aggregator)
Fan-outSending one request on to many services
Join in memoryMerging results in the application instead of in a database
Parallel callsCalls started at the same time, so they overlap
Sequential callsCalls made one after another because each needs the last answer
Tail latencyThe slowest few calls, which decide how long the whole page takes
Partial responseAn answer with some parts missing, because an optional service failed
FallbackA safe substitute (cached data, a default) when a call fails
DeadlineThe total time a request may take, shared by all its calls
Read modelA separate, ready-made view of data, built for fast reading
AggregatorA service whose main job is to compose other services

09Pros, Cons and Trade-offs

βœ… Pros
  • Simple to build and understand
  • Needs no new database or pipeline
  • Always reads live data from the owner
  • Keeps each service independent
  • Clients make one call instead of many
  • One place to handle failures and fallbacks
⚠️ Cons
  • Slower than one query: network calls and an in-memory join
  • More services in the path means less availability
  • Poor for big joins, large lists and filters across services
  • No consistent snapshot: services answer at slightly different moments
  • The composer can become a bottleneck or a hidden monolith
  • Fan-out multiplies the load on the services

Trade-offs

ChoiceWe gainWe lose
Parallel callsTime of the slowest call onlyMore load at once, and more code to handle many results
Sequential callsSimple logic, can use earlier answersTime adds up with every call
Fail the whole pageSimple, the data is always completeOne small service can take the page down
Partial page + fallbackA page that works most of the timeUsers may see missing parts, and you must design those states
Cache composed answersFast and cheapData may be stale for a while
Read model instead of compositionFast queries, filters and sorting across servicesMore moving parts and eventual consistency

10Common Problems and Mistakes

Common mistakes

  1. Calling in a loop. Fetching the reviews for 50 products with 50 separate calls (the N+1 problem). Use a batch call.
  2. Everything sequential. Calls that do not depend on each other still wait in line.
  3. No timeout. One stuck service freezes every request that touches it.
  4. All-or-nothing for everything. A missing recommendations box should not break checkout.
  5. Joining big lists in memory. Merging thousands of rows from two services is slow and uses a lot of memory.
  6. Forgetting availability maths. Ten services at 99.9% each give only about 99.0% for a page that needs all of them.
  7. Business rules in the composer. It slowly becomes a second, untested application.

Things to watch

🐌Tail latency
With parallel calls, the page is only as fast as its slowest service on that request.
πŸ“‰Multiplied failure
Each required service lowers page availability. Make as many as possible optional.
πŸ•°οΈInconsistent snapshot
The price may come from one moment and the stock from another. Fine for pages, risky for money.
πŸ“ˆLoad amplification
One page view can become dozens of service calls. Cache, batch and limit fan-out.

11Real-World Examples

πŸ›οΈOnline shops
A product page gathers product, price, stock, reviews and offers from different services.
πŸ“±Mobile backends
A backend for frontend returns one JSON for a whole screen, so the phone makes one request.
πŸ•ΈοΈGraphQL gateways
Federated GraphQL setups let each team own part of the graph, and a gateway composes the answer.
🏦Banking overviews
A home screen shows accounts, cards and recent activity pulled from separate systems.
🎬Streaming home pages
A home page combines your profile, watch list, recommendations and promotions.
🧾Order history
Orders, payments and shipments are shown together, joined by order id.
πŸ“Note
When the same cross-service question is asked all day, with filters and sorting, many teams build a CQRS read model or a search index instead. Composition is best for simple, live, small answers.
Mini case: product page with a fallback
πŸ“±Phone
→↓1 call
🧩BFFdeadline 150 ms
→↓product + price ok
⭐Reviewstoo slow: skipped
Answered in time Skipped, page still loads
Reviews are slow, so the composer shows the page without them.

12Related Topics to Read Next

API Gateway Pattern→

A gateway is a common place to put composition for every client.

Backend for Frontend (BFF)β†’

A BFF composes exactly the data one kind of screen needs.

Database per Service→

The reason there is no single join, and why composition is needed.

CQRS→

A read model is the alternative when composition is too slow or too limited.

Circuit Breaker→

Protects the composer and the services when one of them fails.

Timeouts and Deadlines→

Every call in a composition needs a limit on how long it may take.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • βœ”What: one composer calls many services and joins the answers in memory.
  • βœ”Who: an API gateway, a BFF, an aggregator service or a GraphQL layer.
  • βœ”Time: parallel = slowest call. Sequential = sum of calls.
  • βœ”Availability: required services multiply: a to the power of N. Make parts optional.
  • βœ”Failure: timeouts, deadlines, fallbacks, partial responses, circuit breakers.
  • βœ”Weak at: big joins, long lists, filtering across services, consistent snapshots.
  • βœ”Alternative: a CQRS read model or a search index built from events.
  • βœ”One line: β€œAsk every service in parallel, combine the answers, and never let one slow part sink the page.”
← Previous
Timeouts and Deadlines
Next β†’
Anti-Corruption Layer