AlgoViz

Synchronous communication

easy 24 min

In synchronous communication the caller sends a request and needs the response before that piece of work can go on.

Video lesson · Chapter 1 of 5

Hold the phone line open

0:00 / 4:06

Synchronous calls in 75 seconds

1:15Reel coming soon

Theory

Read or listen first. About 2 min.

What it is

Synchronous communication is a conversation where the asker waits for the answer. A client sends a request, the server does the work, and the client continues when the response or an error arrives. Loading a web page, logging in and running a database query usually work this way.

It helps to separate two things. Waiting for the result is about the conversation: the next step cannot start without the answer. Blocking a thread is about the code: while waiting, the thread does nothing else. A program can wait for a result without blocking a thread, by using an event loop or coroutines.

Why it exists

It is the simplest way for two programs to work together. The order of events is clear, the result is there when you need it, and an error appears where you can handle it. When a person is waiting on a screen, that is usually what you want.

The price is coupling in time. Both sides must be up together, and a slow server makes a slow caller. When many requests wait at once, the caller runs out of threads, connections or memory. Knowing these limits tells you when a synchronous call is right and when a message is better.

A short history

  1. 1961

    John Little publishes a proof of the law that links arrivals, waiting time and the number of items in a system. It tells us how many calls are waiting.

  2. April 1988

    RFC 1050 specifies Sun's remote procedure call protocol: one call message, one reply message.

  3. May 1996

    RFC 1945 describes HTTP/1.0, the request and response protocol of the early web.

  4. January 1997

    RFC 2068 specifies HTTP/1.1, which keeps connections open for several requests by default.

  5. May 2015

    RFC 7540 specifies HTTP/2, where many requests share one connection at the same time.

  6. June 2022

    RFC 9114 specifies HTTP/3, which carries HTTP over QUIC instead of TCP.

Words to know

Request and response
One message asks, one message answers.
Blocking
The thread does nothing else while it waits.
Non-blocking
The thread serves other work while the result is on its way.
Temporal coupling
Both sides must be available at the same moment.
Thread pool
A fixed number of threads that serve requests. When all wait, new requests queue.
Fan-out
One request that causes several calls, often in parallel.
Cascading failure
One slow or failed part makes its callers fail too.

How it works

Step through the idea, or press Play.

Step 1 of 3

Ask. The caller sends a request and keeps the place open

Understand it

Start here

The phone call story

Imagine calling a cinema in the middle of your homework. Until somebody answers your question, you hold the phone and the homework waits.

Are there any seats left?
4:00CINEMAAny seats?

A phone call needs both people at the same moment. That is what synchronous means.

The idea

What it looks like

One request

Characteristics

  • The caller waits

    The next step needs the answer.

  • Request and response

    Every question gets one answer or one error.

  • Result at once

    Success or failure is known right away.

  • Simple to think about

    Steps happen in the order you read them.

  • Tight coupling

    Both sides must be up, and fast, together.

Common protocols

ProtocolWhere you meet it
HTTP and HTTPS: REST, GraphQLBrowsers, apps, public APIs
gRPC unary callsBetween services, see RPC
SOAPOlder enterprise services
XML-RPC and JSON-RPCSimple remote calls
SQL queriesAn application and its database

Patterns

Four common shapes

  1. 1

    Direct call

    One service calls another: the order service sends GET /users/123 and waits for 200 OK with the user.

  2. 2

    Through a gateway

    Clients talk to one API gateway, which routes each request to service A or B and returns the answer.

  3. 3

    Chain

    A calls B, B calls C, C calls D. Each waits for the one after it.

  4. 4

    Aggregator

    One service calls users, orders and products, and joins the answers. Independent calls run in parallel.

A chain of three

A user's request goes to service A with 50 ms of own work, then service B with 100 ms, then service C with 150 ms. C answers after 150 ms, B after 250 ms, and the user waits 300 ms.
Own work is 50, 100 and 150 ms. The user waits at least 300 ms. Network time comes on top.

The aggregator

A user's request passes an API gateway to an aggregator, which calls users at 50 ms, orders at 100 ms and products at 150 ms at the same time.
In parallel, the wait is set by the slowest call: 150 ms instead of 300.

Chains

Delays add, availabilities multiply

Latency: in a row or side by side

Tchain=∑ti=50+100+150=300 msTparallel=max⁡ti=150 msT_{\text{chain}} = \sum t_i = 50 + 100 + 150 = 300\text{ ms} \qquad T_{\text{parallel}} = \max t_i = 150\text{ ms}
Averages add in a chain. Percentiles do not simply add: see below.

Availability of a chain

A=0.9994≈0.9960.4%×43,200 min≈173 min a monthA = 0.999^4 \approx 0.996 \qquad 0.4\% \times 43{,}200\text{ min} \approx 173\text{ min a month}
Four services that must all answer, each up 99.9% of the time and failing independently. Retries and fallbacks improve it.

Blocking

What waiting costs

A server with blocking calls gives each request a thread. While it waits, the thread holds memory and does nothing useful.

Three threads, one slow service

Request 3 has not started, although the processor is idle.

Arithmetic

How many threads are waiting?

Little's law: how many calls are waiting?

L=λW200 req/s×0.5 s=100 threadsL = \lambda W \qquad 200\text{ req/s} \times 0.5\text{ s} = 100\text{ threads}
With 100 threads this pool is exactly full at 200 requests a second. There is no room for the smallest bump.

A pool of 100 threads, 0.5 s per request

ArrivalsThreads neededWhat happens
100 a second50Half the pool is busy
200 a second100Full. Random bumps already queue
250 a second12550 a second more than it can serve. After 60 s, 3,000 wait
100 a second, dependency slows to 2 s200Full, although traffic did not change
At 250 a second the line grows steadily. A request that joins behind 3,000 others waits 3,000 / 200 = 15 s.

What helps

  • Timeouts that fit the caller's budget
  • Circuit breakers
  • Bulkheads: separate pools for each dependency
  • Watching latency percentiles
  • Non-blocking I/O for work that mostly waits

What goes wrong

  • The thread pool is used up under load
  • Processors idle while requests wait
  • One slow service blocks many: cascading failure
  • Memory for every waiting thread
  • Limited concurrency
TypeScript
// Do not wait forever. A cancelled call also frees the connection.const response = await fetch(url, { signal: AbortSignal.timeout(3000) });if (!response.ok) throw new Error("HTTP " + response.status);
How to choose the number is in timeouts. Stopping calls to a broken service is in circuit breaker.

How one slow service spreads

Trade-offs

Synchronous or asynchronous?

AspectSynchronousAsynchronous
CouplingTight: the caller depends on the callee nowLoose: through a broker
ResultComes with the responseComes later; other data is eventually consistent
ErrorsImmediate feedbackRetries and dead letter queues
ScalingLimited by what waits: threads, connections, the slowest partProducers and consumers scale separately
ComplexitySimple to understandOrdering, duplicates, idempotency
DebuggingEasier, a linear flowHarder. Both need tracing across services
The other side is asynchronous communication.

Choose synchronous when

  • An immediate response is required
  • The user is waiting for the result
  • A simple request and response is enough
  • Errors must be reported at once
  • The steps can share one database transaction inside one service

Choose asynchronous when

  • The work takes long
  • Throughput matters more than an instant result
  • The data may become consistent later
  • Services should be decoupled
  • Work can be queued and done later

Decide

When to use it

Use cases

Use caseCallWhy, and what to watch
LoginPOST /auth/login returns 200 and a sessionThe user cannot go on without it
PaymentPOST /payments/charge returns 201The user wants to know. Send an idempotency key, and allow for a pending result that is confirmed later
Stock checkGET /inventory/SKU123 returns stock 5Good for display. It does not prevent overselling: reserve the item at checkout
SearchGET /search?q=shoesResults are the page
Form validationPOST /validate returns valid trueUsername or email taken? Check again when saving
Transfer between two accounts in one bank's databasePOST /transfer returns completedOne database transaction, all or nothing. Transfers between banks are usually not instant

Do not make people wait for this

WorkInstead
Sending emailQueue it. The user does not need to wait for the mail server
Report generationRun it in the background and notify when done
Image processingUpload quickly, process in the background
Analytics eventsSend to a queue and move on

Build it well

Four implementation rules

  1. 1

    Always set timeouts

    Connection and read timeouts, and a total budget. In Python's requests library one number is used for both connect and read, and it is not a limit on the total time.

  2. 2

    Reuse connections

    A pool avoids a new TCP and TLS handshake for every call.

  3. 3

    Run independent calls in parallel

    Promise.all, a thread pool or goroutines. Cancel the rest when one failure makes them useless.

  4. 4

    Tell errors apart

    A timeout, a network error and an HTTP error need different actions. Retry only what is safe: see retries.

Python
import requestsfrom requests.adapters import HTTPAdapterfrom urllib3.util.retry import Retrydef create_session():    session = requests.Session()                    # reuses connections    retry = Retry(total=2, backoff_factor=0.2,                  status_forcelist=[429, 502, 503, 504],                  allowed_methods=["GET", "HEAD"])  # only calls that are safe to repeat    session.mount("https://", HTTPAdapter(max_retries=retry, pool_maxsize=20))    return sessionsession = create_session()def get_user(user_id, token):    try:        response = session.get(f"https://api.example.com/users/{user_id}",                               headers={"Authorization": f"Bearer {token}"},                               timeout=(0.5, 2))    # connect, read        response.raise_for_status()        return response.json()    except requests.Timeout as err:        raise TimeoutError("users did not answer in time") from err    except requests.HTTPError as err:        raise RuntimeError(f"HTTP {err.response.status_code}") from err
The same client in Python. Retries multiply the time, so count them in the budget.

Summary

The whole topic in one minute.

A synchronous call means the caller needs the answer before it can go on. It is easy to understand and gives feedback at once, so use it when someone is waiting for the result.

Delays in a chain add up, availabilities multiply, and waiting requests occupy threads: arrivals times waiting time. Keep chains short, run independent calls in parallel, set timeouts, and move work nobody waits for into a queue.

  • The caller needs the answer before it can go on.
  • Waiting for a result is not the same as blocking a thread.
  • Chains add delays and multiply availabilities; parallel calls cost the slowest one.
  • Waiting calls = arrivals x waiting time.
  • Timeouts, pools and breakers keep one slow service from stopping the rest.

Sources