Understanding Communication Fundamentals

1. Understanding Synchronous Communication

PropertyDetail
DefinitionCaller blocks until callee responds
ProtocolsHTTP/REST, gRPC, GraphQL, SOAP
CouplingTemporal (both must be available)
LatencySum of all calls in chain
Use WhenImmediate response needed; query operations
Avoid WhenLong chains; high-volume fanout

Example: Synchronous REST Call (Java + Spring)

@RestController
public class OrderController {
    private final RestClient paymentClient;

    @PostMapping("/orders")
    public OrderResponse create(@RequestBody OrderRequest req) {
        // Blocking call to Payment Service
        PaymentResult result = paymentClient.post()
            .uri("/payments")
            .body(req.toPayment())
            .retrieve()
            .body(PaymentResult.class);
        return new OrderResponse(result.orderId(), result.status());
    }
}

2. Understanding Asynchronous Communication

PropertyDetail
DefinitionSender does not wait; consumer processes later
MechanismsMessage queues, event streams, webhooks
CouplingTemporal decoupling via broker
ReliabilityBroker persists messages until consumed
Use WhenLong-running ops, fanout, decoupling
Avoid WhenCaller needs immediate result

Example: Async Publishing (Java + Kafka)

@Service
public class OrderService {
    private final KafkaTemplate<String, OrderEvent> kafka;

    public void placeOrder(Order order) {
        orderRepo.save(order);
        kafka.send("orders.placed", order.id(), 
                   new OrderEvent(order.id(), order.items(), order.total()));
        // Returns immediately; downstream services react asynchronously
    }
}

3. Understanding Communication Protocols

ProtocolStyleFormatBest For
HTTP/RESTSync, request/responseJSONPublic APIs, broad compatibility
gRPCSync/streamingProtobufInternal high-perf service-to-service
GraphQLSync, queryJSONBFF, flexible client queries
WebSocketBi-directional streamAnyReal-time UI updates
AMQP (RabbitMQ)Async messagingAnyWork queues, routing
Kafka ProtocolAsync log/streamAvro/Protobuf/JSONEvent streaming, replay
MQTTAsync pub/sub (lightweight)BinaryIoT, low bandwidth
NATSAsync pub/sub (high perf)AnyCloud-native messaging

4. Synchronous vs Asynchronous Communication

Synchronous

  • Pros: Simple, immediate response, easy debugging
  • Pros: Strong contract enforcement
  • Cons: Temporal coupling, cascading failures
  • Cons: Latency adds across chain

Asynchronous

  • Pros: Loose coupling, resilient to outages
  • Pros: Natural backpressure, scalable fanout
  • Cons: Eventual consistency complexity
  • Cons: Harder debugging/tracing
ScenarioChoose
User-facing GET (need result now)Sync REST/gRPC
Order placed → notify shipping/billingAsync event
Multi-step business workflowAsync + Saga
Real-time data streamAsync streaming (Kafka)

5. Understanding Message Brokers

BrokerModelStrength
Apache KafkaLog-based, partitionedHigh throughput, replay, streaming
RabbitMQQueue + exchange routing (AMQP)Flexible routing, work queues
AWS SQSManaged queueSimplicity, integrated with AWS
AWS SNSPub/sub fanoutNotification fanout
NATS / NATS JetStreamPub/sub, streamsLow latency, cloud-native
Apache PulsarTiered storage, multi-tenantGeo-replication, large scale
Redis StreamsIn-memory logSimple, fast, with consumer groups

6. Understanding RPC Patterns

RPC VariantDescriptionTooling
Unary RPCOne request, one responsegRPC, Thrift
Server StreamingOne request, stream of responsesgRPC
Client StreamingStream of requests, one responsegRPC
Bi-directional StreamingBoth sides streamgRPC, WebSocket
JSON-RPCLightweight RPC over HTTPVarious

Example: gRPC Service (Protobuf)

syntax = "proto3";
service PaymentService {
  rpc Charge(ChargeRequest) returns (ChargeResponse);
  rpc StreamReceipts(StreamRequest) returns (stream Receipt);
}
message ChargeRequest { string order_id = 1; int64 amount_cents = 2; }
message ChargeResponse { string status = 1; string txn_id = 2; }

7. Understanding Event-Driven Architecture

ConceptDescription
EventImmutable record of something that happened
ProducerService that emits events; owns the schema
ConsumerService that reacts; multiple consumers per event
BrokerDurable transport (Kafka, Pulsar, RabbitMQ)
Topic / StreamNamed channel partitioning events by type
ChoreographyServices react to events; no central controller

Event Flow

[Order Service] --OrderPlaced--> [Kafka topic: orders]
                                         ↓
                ┌───────────────────────┼────────────────────┐
                ↓                       ↓                    ↓
        [Payment Service]      [Inventory Service]   [Notification Svc]
        

8. Understanding Pub/Sub Model

ElementRole
PublisherSends message to topic; unaware of subscribers
TopicLogical channel; multiple subscribers receive copies
SubscriberIndependent consumer of topic
SubscriptionDurable cursor (Kafka consumer group, SNS sub)
Delivery SemanticsAt-least-once typical; exactly-once with effort

9. Understanding Request/Reply Model

ModeHowExample
Sync Request/ReplyHTTP request → HTTP responseREST call
Async Request/ReplySend to request queue, listen on reply queue (correlation ID)RabbitMQ RPC, JMS
CallbackSender provides callback URL/queueWebhooks

Example: Async Request/Reply with Correlation ID

String correlationId = UUID.randomUUID().toString();
rabbit.convertAndSend("requests", request, msg -> {
    msg.getMessageProperties().setCorrelationId(correlationId);
    msg.getMessageProperties().setReplyTo("replies." + serviceId);
    return msg;
});
// Consumer matches correlationId to deliver response back to caller

10. Understanding Push vs Pull Communication

ModelMechanismProsCons
PushBroker delivers to consumer (e.g., webhooks, RabbitMQ)Low latencyCan overwhelm consumer; needs backpressure
PullConsumer fetches at its pace (e.g., Kafka, SQS poll)Natural backpressure, simple scalingPolling overhead, latency
Long PollingConsumer holds connection until data readyReduces empty pollsConnection management cost