Search Sreeni's Insights

Filter by content type
technical July 21, 2016 7 min read

Microservices - Part 2

Microservices Part 2 compares synchronous HTTP and asynchronous messaging through timeouts, retries, Service Bus, duplicate handling and eventual consistency for practical guidance.

Share:

Microservices - Part 2

Once a system is distributed across services, communication becomes an architecture decision rather than a private implementation detail. A pricing request may need an immediate answer, while a reporting update can be processed later. In the previous article, we discussed service boundaries, Conway’s Law and the hidden costs of microservices. In this article, we are going to compare synchronous HTTP communication with asynchronous messaging.

TL;DR Summary

  • Synchronous communication waits for the receiver to return a response.
  • Asynchronous messaging records a message and allows the consumer to process it independently.
  • A synchronous chain creates a larger availability and latency boundary.
  • HTTP calls need timeouts, bounded retries and a circuit breaker where appropriate.
  • Service Bus consumers need duplicate handling, dead-letter monitoring and correlation ids.
  • Asynchronous processing introduces eventual consistency and a user-interface responsibility.
  • Use the simplest communication which satisfies the business timing requirement.

Challenges

The chain is failing as a unit

An Order service calling Pricing and then Documents synchronously is easy to understand on a whiteboard. During an incident, a slow Documents dependency is holding threads in every upstream service. The chain is increasing the customer impact of one failure.

A timeout does not tell the truth

When a client times out, the server may have completed the operation. Retrying a non-idempotent command can create a duplicate order. The caller must know whether the operation is safe to retry, and the command needs an idempotency key when the business effect is important.

Asynchronous work is less visible

A queue makes the original request fast, but the user may not know whether the document or reporting action is completed. Correlation ids, status APIs and dashboards are required. Otherwise a visible timeout is exchanged for an invisible delay.

What are synchronous and asynchronous calls?

Synchronous communication waits for a receiver to return a response, while asynchronous communication records a message or event and allows the consumer to process it independently.

In simple terms, HTTP is asking a colleague to finish the answer now, while messaging is leaving a reliable work item which the colleague will pick up. Neither option is automatically more modern.

An everyday analogy is ordering food. Asking a waiter whether a table is available is synchronous. Leaving an order ticket in the kitchen is asynchronous: the customer can sit down, but the kitchen needs a way to show whether the meal is ready.

Why the communication choice is important?

The choice is defining latency, failure propagation and consistency. A fund-price read may require an immediate response, while a search-index update should not make a publishing request wait. The API must be honest about which user action is complete and which downstream work is still progressing.

The following diagram compares both paths:

Synchronous versus asynchronous communication
Synchronous versus asynchronous communication

The synchronous panel is showing Order calling Pricing and then Documents over HTTP. The red X is showing that Documents failing can break the complete request chain. The asynchronous panel is showing Order publishing to a Service Bus queue or topic, with Pricing and Documents subscribing independently. The message path is moving failure to a retry boundary, not removing failure.

Synchronous HTTP with protection

Synchronous calls are suitable for a query where the caller cannot continue without the answer. A fund summary API can call Pricing when it must display the current price. It should not wait indefinitely:

var policy = Policy
    .Handle<HttpRequestException>()
    .OrResult<HttpResponseMessage>(
        response => (int)response.StatusCode >= 500)
    .WaitAndRetryAsync(
        2,
        retry => TimeSpan.FromMilliseconds(100 * retry));

using (var timeout = new CancellationTokenSource(
    TimeSpan.FromSeconds(2)))
{
    var response = await policy.ExecuteAsync(
        () => priceClient.GetAsync("/funds/123/price",
            timeout.Token));
    response.EnsureSuccessStatusCode();
}

Polly is commonly used by .NET teams for retry policies. The retry count must be small, and the operation must be safe to retry. A circuit breaker can stop sending traffic to an unhealthy service, but it should return a meaningful response to the caller. Retrying five times in every layer is multiplying latency.

Asynchronous Service Bus communication

An event such as FundPricePublished can be published after the authoritative transaction:

var client = TopicClient.CreateFromConnectionString(
    connectionString, "fund-events");

var brokered = new BrokeredMessage(
    JsonConvert.SerializeObject(new
    {
        FundId = 123,
        Price = 10.50m,
        PublishedAt = DateTime.UtcNow
    }));
brokered.Properties["EventType"] = "FundPricePublished";

await client.SendAsync(brokered);

The Search consumer can update its index later:

var subscription = SubscriptionClient.CreateFromConnectionString(
    connectionString, "fund-events", "search-indexer");

subscription.OnMessageAsync(async message =>
{
    var item = JsonConvert.DeserializeObject<FundPricePublished>(
        message.GetBody<string>());
    if (!await index.HasProcessedAsync(message.MessageId))
    {
        await index.UpdatePriceAsync(item);
        await index.MarkProcessedAsync(message.MessageId);
    }
});

The user interface is not receiving “all work is finished” unless the system can prove it. It can return an accepted status and show “index update pending”. The operations dashboard is monitoring age, failures and dead letters.

Choosing the boundary

RequirementCommunicationReason
Read current price before showing resultSynchronous HTTPCaller needs the value now
Update Search after price publicationAsynchronous eventIndex can be eventually consistent
Send a notificationAsynchronous messageEmail is independent of the command
Validate an order before commitSynchronous call or local domain logicInvalid request must be rejected
Run a long document conversionAsynchronous commandWork can outlive the HTTP request

In our case, queries and validation stay synchronous where the response is required. Reporting, email and search projection are asynchronous. A command which changes holdings uses idempotency before either style is selected.

Observability across the boundary

The request is carrying a correlation id such as fund-query-123. The HTTP client is adding it to a header, and the publisher is copying it into Service Bus properties. The Pricing log, Order log and Search projection log can then be joined when support is investigating one customer request.

The synchronous dashboard is showing timeout count, retry count, circuit state and dependency latency. A retry is not being counted as a successful customer request until the final response is known. The asynchronous dashboard is showing active messages, oldest message age, delivery count and dead-letter count. These values are separating a slow consumer from a failed publisher.

The message schema stays factual and versioned:

public sealed class FundPricePublished
{
    public string MessageId { get; set; }
    public string CorrelationId { get; set; }
    public int FundId { get; set; }
    public decimal Price { get; set; }
}

The consumer does not rely on message order unless the subscription is configured and the business requirement supports it. If two price events arrive out of order, the event timestamp or sequence is checked before the read model is updated. This is more reliable than assuming that network delivery preserves business order.

An incident exercise uses both styles. The team stops Pricing and observes the bounded synchronous error, then sends a price event while Search is unavailable and checks that the message is retained. The result is compared with the customer promise: immediate price errors are visible, while index delay is acceptable only when the UI explains it.

The communication decision is also influencing deployment order. A synchronous consumer must be deployed before a publisher starts sending a new required field. An asynchronous consumer can ignore an optional field, but a filter or deserializer which is rejecting the message will move it to dead-letter. Compatibility is therefore being checked before the release is promoted.

For a fund document conversion, the API is accepting a request and returning a tracking id. The worker is publishing DocumentConverted after the Blob output is durable. The UI is polling a status resource rather than holding an HTTP connection open. This is giving the user a useful answer while allowing the worker to retry a transient converter failure.

The choice is revisited when the business timing changes. A report which was allowed to be eventually consistent may become part of an order decision and then require synchronous validation. Communication style is not a permanent label on a service; it depends on the promised contract.

Must Do and Don’ts

  • Must Do: Set a timeout on every synchronous call, otherwise one dependency can hold the complete request indefinitely.
  • Must Do: Retry only transient failures and only when the operation is safe, because a blind retry can duplicate a holding.
  • Must Do: Put a correlation id in HTTP headers and Service Bus properties, so support can trace one fund operation.
  • Must Do: Display eventual consistency to the user when a projection is delayed, otherwise the screen will appear incorrect.
  • Don’t: build a long synchronous chain for independent work, because the weakest dependency becomes the availability limit.
  • Don’t: acknowledge a message before its side effect is durable, otherwise the message can be lost after a process crash.

Wrap up

In this article, we have looked at synchronous HTTP, Polly timeouts and retries, asynchronous Service Bus messages, duplicate handling and eventual consistency. Communication is a business timing choice, not only a technology preference. I hope this article provided you some insights into distributed communication. In the next article, I will walk you through the API Gateway pattern as one front door for many services.

Related Posts