Synchronous communication
easy 24 minIn 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
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
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.
April 1988
RFC 1050 specifies Sun's remote procedure call protocol: one call message, one reply message.
May 1996
RFC 1945 describes HTTP/1.0, the request and response protocol of the early web.
January 1997
RFC 2068 specifies HTTP/1.1, which keeps connections open for several requests by default.
May 2015
RFC 7540 specifies HTTP/2, where many requests share one connection at the same time.
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.
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.
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
| Protocol | Where you meet it |
|---|---|
| HTTP and HTTPS: REST, GraphQL | Browsers, apps, public APIs |
| gRPC unary calls | Between services, see RPC |
| SOAP | Older enterprise services |
| XML-RPC and JSON-RPC | Simple remote calls |
| SQL queries | An application and its database |
Patterns
Four common shapes
- 1
Direct call
One service calls another: the order service sends
GET /users/123and waits for 200 OK with the user. - 2
Through a gateway
Clients talk to one API gateway, which routes each request to service A or B and returns the answer.
- 3
Chain
A calls B, B calls C, C calls D. Each waits for the one after it.
- 4
Aggregator
One service calls users, orders and products, and joins the answers. Independent calls run in parallel.
A chain of three
The aggregator
Chains
Delays add, availabilities multiply
Latency: in a row or side by side
Availability of a chain
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
Arithmetic
How many threads are waiting?
Little's law: how many calls are waiting?
A pool of 100 threads, 0.5 s per request
| Arrivals | Threads needed | What happens |
|---|---|---|
| 100 a second | 50 | Half the pool is busy |
| 200 a second | 100 | Full. Random bumps already queue |
| 250 a second | 125 | 50 a second more than it can serve. After 60 s, 3,000 wait |
| 100 a second, dependency slows to 2 s | 200 | Full, although traffic did not change |
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
// 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 one slow service spreads
Trade-offs
Synchronous or asynchronous?
| Aspect | Synchronous | Asynchronous |
|---|---|---|
| Coupling | Tight: the caller depends on the callee now | Loose: through a broker |
| Result | Comes with the response | Comes later; other data is eventually consistent |
| Errors | Immediate feedback | Retries and dead letter queues |
| Scaling | Limited by what waits: threads, connections, the slowest part | Producers and consumers scale separately |
| Complexity | Simple to understand | Ordering, duplicates, idempotency |
| Debugging | Easier, a linear flow | Harder. Both need tracing across services |
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 case | Call | Why, and what to watch |
|---|---|---|
| Login | POST /auth/login returns 200 and a session | The user cannot go on without it |
| Payment | POST /payments/charge returns 201 | The user wants to know. Send an idempotency key, and allow for a pending result that is confirmed later |
| Stock check | GET /inventory/SKU123 returns stock 5 | Good for display. It does not prevent overselling: reserve the item at checkout |
| Search | GET /search?q=shoes | Results are the page |
| Form validation | POST /validate returns valid true | Username or email taken? Check again when saving |
| Transfer between two accounts in one bank's database | POST /transfer returns completed | One database transaction, all or nothing. Transfers between banks are usually not instant |
Do not make people wait for this
| Work | Instead |
|---|---|
| Sending email | Queue it. The user does not need to wait for the mail server |
| Report generation | Run it in the background and notify when done |
| Image processing | Upload quickly, process in the background |
| Analytics events | Send to a queue and move on |
Build it well
Four implementation rules
- 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
Reuse connections
A pool avoids a new TCP and TLS handshake for every call.
- 3
Run independent calls in parallel
Promise.all, a thread pool or goroutines. Cancel the rest when one failure makes them useless. - 4
Tell errors apart
A timeout, a network error and an HTTP error need different actions. Retry only what is safe: see retries.
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 errSummary
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.