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.

Chain, parallel and a full pool

Read it, run it, change a line and run it again.

Loading editor…

Runs in well under two seconds. The services are functions that sleep, so you can measure the difference yourself.

The same in TypeScript
interface User { id: string; name: string; email: string }async function getJson<T>(path: string, token: string, ms = 2000): Promise<T> {  try {    const response = await fetch("https://api.example.com" + path, {      headers: { Authorization: "Bearer " + token },      signal: AbortSignal.timeout(ms), // this request waits; the event loop does not    });    if (!response.ok) throw new Error("HTTP " + response.status);    return (await response.json()) as T;  } catch (err) {    if (err instanceof DOMException && err.name === "TimeoutError") throw new Error("Request timed out");    throw err;  }}// Aggregator: independent calls run in parallelasync function getUserWithOrders(userId: string, token: string) {  const [user, orders] = await Promise.all([    getJson<User>("/users/" + userId, token),    getJson<unknown[]>("/users/" + userId + "/orders", token),  ]);  return { user, orders };}// Chain: right only when each step needs the one before itasync function processOrder(orderId: string, token: string) {  const order = await getJson<{ userId: string; sku: string }>("/orders/" + orderId, token);  const [user, inventory] = await Promise.all([ // both need only the order    getJson<User>("/users/" + order.userId, token),    getJson<{ stock: number }>("/inventory/" + order.sku, token),  ]);  return { order, user, inventory };}
The same in Go
package mainimport (	"context"	"encoding/json"	"errors"	"fmt"	"net/http"	"time"	"golang.org/x/sync/errgroup")type User struct {	ID    string `json:"id"`	Name  string `json:"name"`	Email string `json:"email"`}type Order struct {	ID string `json:"id"`}var client = &http.Client{Timeout: 5 * time.Second} // one client, reuses connectionsfunc getJSON(ctx context.Context, url string, out any) error {	req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)	if err != nil {		return err	}	resp, err := client.Do(req) // this goroutine waits here	if err != nil {		if errors.Is(err, context.DeadlineExceeded) {			return fmt.Errorf("timed out: %w", err)		}		return fmt.Errorf("request failed: %w", err)	}	defer resp.Body.Close()	if resp.StatusCode != http.StatusOK {		return fmt.Errorf("HTTP %d", resp.StatusCode)	}	return json.NewDecoder(resp.Body).Decode(out)}// Two independent calls side by side. The first error cancels the other.func userWithOrders(ctx context.Context, id string) (User, []Order, error) {	var user User	var orders []Order	g, ctx := errgroup.WithContext(ctx)	g.Go(func() error { return getJSON(ctx, "https://api.example.com/users/"+id, &user) })	g.Go(func() error { return getJSON(ctx, "https://api.example.com/users/"+id+"/orders", &orders) })	return user, orders, g.Wait()}func main() {	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)	defer cancel()	user, orders, err := userWithOrders(ctx, "user-123")	fmt.Println(user, len(orders), err)}