Request-Reply over Messaging & REST vs AMQP
"Send a pair of Request-Reply messages, each on its own channel." — Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns, "Request-Reply" (source)
Summary: how to get an answer back through a broker (correlation id, return address, reply queue, RabbitMQ Direct Reply-To, Kafka reply topics, Redis reply streams), why making a queue behave like a function call is usually a mistake, and when plain REST or gRPC is simply the right tool. Focus: the reply leg and its failure modes: timeouts, orphaned and duplicate replies, starvation of the caller, and the choices that replace waiting (202 plus a status resource, SSE, WebSocket, webhook). Learning goal: after this page you can build a bounded RPC over RabbitMQ in Go or PHP, say why it is a last resort, choose between REST, gRPC, broker RPC and an asynchronous reply with a decision table, and propagate correlation and trace ids across every hop.
This is the Routing & Consumers chapter that deals with conversations, not one-way flow. It owns correlation ids, reply queues, RabbitMQ Direct Reply-To, Kafka request-reply pitfalls, the sync-over-async anti-pattern and the "when REST is simply right" decision. It does not re-teach the pieces next to it: competing consumers own scaling the replier, message acknowledgment owns ack mechanics, idempotent consumers own the dedup table, retry and backoff own the retry schedule, and routing topologies own exchange design. The broker deep dives are RabbitMQ, Kafka and Redis Streams & Pub/Sub.
Page map
| If you are looking for | Go to |
|---|---|
| The one-minute version: three tables | Everything in one minute |
| Where Request-Reply, Return Address and Correlation Identifier come from | Where it comes from |
| What actually goes into the request and the reply | Mechanics: anatomy of a call |
| Request-Reply, Correlation Identifier, Return Address in plain words | Concept catalogue |
| One reply queue per call, per client, or shared | Reply queue strategies |
amq.rabbitmq.reply-to, its rules and limits | Direct Reply-To |
| Timeouts, orphaned replies, duplicate replies | Timeouts and orphans, Duplicate replies |
| A blocking HTTP handler waiting on a queue | Sync over async |
202 Accepted plus a status resource | 202 and a status resource |
| Pushing the answer to a browser (SSE, WebSocket, webhook) | Asynchronous reply to a client |
traceparent versus correlation_id | Correlation across hops |
| REST / gRPC versus messaging, one table | Choosing |
| Go: amqp091 RPC with Direct Reply-To and a timeout; net/http alternative | Go |
Laravel: Http client, job plus afterCommit, notification, Reverb, RPC consumer | Laravel |
| RabbitMQ, Kafka and Redis Streams side by side | Broker differences |
| Monolith to distributed | In architecture |
| Latency lab and the starvation demo | Lab |
Everything in one minute
Table 1: the vocabulary.
| Term | Plain words | Where it lives |
|---|---|---|
| Request-Reply | Two one-way messages, each on its own channel, make a conversation | EIP pattern |
| Requestor / Replier | Who asks / who answers | The two roles |
| Return Address | "Send the answer here", written in the request | reply_to in AMQP 0-9-1, reply-to in AMQP 1.0, a header in Kafka |
| Correlation Identifier | "This answer belongs to request X" | correlation_id (AMQP 0-9-1), correlation-id (AMQP 1.0), a header in Kafka |
| Reply queue | Where answers wait for the requestor | Exclusive, long-lived, or the pseudo-queue amq.rabbitmq.reply-to |
| Orphaned reply | An answer nobody is waiting for any more | After a timeout or a client restart |
| Sync over async | A caller that publishes to a queue and then blocks for the answer | The anti-pattern this page is about |
202 Accepted | "Received, not finished; look here for progress" | HTTP (RFC 9110, section 15.3.3) |
Table 2: the mechanism in five lines.
| Step | What happens | Who is responsible |
|---|---|---|
| 1 | Requestor creates a unique id and registers a waiter in a table | Requestor |
| 2 | Requestor publishes the request with correlation_id, reply_to and an expiry | Requestor |
| 3 | Replier does the work and publishes the answer to reply_to | Replier |
| 4 | Replier copies the id into the reply's correlation_id | Replier |
| 5 | Requestor looks the id up; known id completes the waiter, unknown id is dropped | Requestor |
Table 3: which tool for which question.
| Situation | First choice | Why |
|---|---|---|
| A user waits and the answer is a fast read (price, permission, validation) | REST or gRPC with a deadline | Simple, visible, failure is immediate |
| The work takes seconds or minutes, a user started it | 202 plus status resource; push result by SSE or WebSocket | Frees the web worker, honest about time |
| One service tells another to do something, no one waits | Command message, optional reply event | Temporal decoupling, retries owned by the broker |
| Thousands of short-lived clients need broker RPC on RabbitMQ | Direct Reply-To | No queue per client |
| A reply must survive a client reconnect | Reply queue, not Direct Reply-To | Broker buffers the reply |
| Kafka is the only broker and a reply is unavoidable | Reply topic or reply partition with a deadline | Works, but awkward (Kafka) |
| Everything else | Do not use request-reply over a broker | "When in doubt avoid RPC" (RabbitMQ tutorial 6) |
Where it comes from
Hohpe and Woolf's Enterprise Integration Patterns describes a conversation as two independent message deliveries. Request-Reply defines the two legs, Return Address carries the reply destination, and Correlation Identifier ties the response to its original request. The opening quotation gives the whole pattern in twelve words.
The requestor can use Synchronous Block, which suspends the caller until a reply, or Asynchronous Callback, which lets a listener complete the matching pending operation. The callback approach allows one reply consumer to serve many outstanding requests, but the caller may still choose to wait synchronously. A callback implementation alone does not remove temporal coupling.
RabbitMQ tutorial 6 recommends avoiding RPC when an asynchronous processing pipeline fits. Broker RPC needs explicit timeout, error, duplicate and retry behaviour; it does not inherit local-call semantics. HTTP's alternative is a 202 Accepted response with a status monitor: RFC 9110 says acceptance does not guarantee processing or eventual success. A Location response header and Retry-After are useful API conventions in this chapter, not mandatory headers imposed on every 202 response by the RFC.
Why request-reply over a broker exists
Messaging is one-way by design. That is its strength: the sender does not wait, the receiver does not need to be up, the broker absorbs bursts. But some interactions are genuinely two-way: "what is the price of A-1?", "reserve this seat". If those interactions must cross a broker (because the broker is the only path between two systems, or because you want its load balancing and routing), you rebuild a call out of two messages.
| You gain | You pay |
|---|---|
| Load balancing across repliers for free (competing consumers on the request queue) | A reply path to build, secure and clean up |
| The replier can be down for a moment; the request waits in the queue | The caller still waits, so "down for a moment" becomes latency or a timeout |
| Routing by queue name, exchange, header | A correlation table, timeouts, orphan handling |
| Same transport for commands, events and replies | Two hops instead of one TCP connection; the broker is on the latency path |
Everyday picture. A restaurant. Standing at the counter until the food is ready is a synchronous call: you cannot leave and the cashier has a queue behind you. Taking a numbered ticket and sitting down is request-reply over messaging: the number is the correlation id, your table is the return address, and the kitchen can be slow without blocking the door. If you walk out, the kitchen still plates a meal for ticket 42: an orphaned reply. "We will text you" is the callback; the screen showing order status is the 202 status endpoint. Standing at the counter while also holding a ticket is sync over async: you pay for both systems and get the benefits of neither.
Three misunderstandings, up front.
- "A queue between two services makes the call asynchronous." Only if the caller stops waiting. A caller that blocks on the reply has the same coupling in time as a direct call, plus a broker hop.
- "A correlation id makes retries safe." It matches replies to requests. It says nothing about whether the work ran twice.
- "Direct Reply-To is a faster reply queue." It is a different guarantee: no buffering, at-most-once, tied to one channel.
Mechanics: anatomy of a call
What the request and the reply carry
| Field | AMQP 0-9-1 property | AMQP 1.0 field | Kafka (record header, by convention) | Redis Streams (entry field, by convention) |
|---|---|---|---|---|
| Return address | reply_to | reply-to | reply-topic, reply-partition | reply_to (a stream or channel name) |
| Correlation id | correlation_id | correlation-id | correlation-id | correlation_id |
| Message identity | message_id | message-id | message-id | the stream entry id, or a field |
| Request expiry | expiration (per-message TTL, milliseconds as a string) | header ttl | none built in; a deadline header you check | none built in; a deadline field you check |
| Trace context | header traceparent | application property | header traceparent | field traceparent |
| Payload type | content_type | content-type | header or schema registry id | field |
On RabbitMQ the doc for Direct Reply-To shows the convention for AMQP 1.0: the requester sets message-id to a globally unique value and the replier copies that identity into its correlation-id (Direct Reply-To). In AMQP 0-9-1 tutorials the requester sets correlation_id directly and the replier copies it. Either way: one id per request, copied into the reply.
The requestor's state
requestor process
pending: map[correlation_id] -> waiter(channel or future) one entry per call in flight
reply consumer: one subscription, shared by all calls started once, at connect time
timers: one deadline per entry remove the entry when it firesThe table is the whole trick. Calls are many, the reply consumer is one, and the id routes each reply to the right waiter. If the process restarts the table is gone; replies that arrive afterwards have no waiter, which is why a restart is the same event as a timeout.
Failure modes in one table
| Failure | What the requestor sees | What it must do |
|---|---|---|
| Replier is down | Request sits in the queue; no reply | Deadline fires, report timeout, do not retry blindly |
| Replier is slow | Reply arrives after the deadline | Drop it (unknown id), tell the replier the request expired if you can |
| Replier crashes after replying, before ack | Request redelivered, a second reply arrives | Ignore the duplicate; make the work idempotent |
| Requestor restarts | Replies arrive for ids it never heard of | Ignore; decide whether to resend the request |
| Reply queue deleted (exclusive queue after disconnect, Direct Reply-To after disconnect) | Replies are dropped by the broker | Reconnect, resend if the call is safe to repeat |
| Broker unavailable | Publish fails or blocks | Fail fast with a deadline; do not hold a worker |
| Poison request | The replier rejects it repeatedly | Dead-letter queue; the requestor times out |
Request has no reply_to | Replier cannot answer | Replier rejects without requeue |
Timeline: the happy path
requestor request queue replier reply queue / reply-to
1 id = c-42; pending[c-42]
2 publish(reply_to=R, id=c-42, ttl=5s) ---->
3 c-42 waits <---- basic.deliver (prefetch 1)
4 work (120 ms)
5 publish to R: correlation_id=c-42 ---->
6 ack request
7 <---------------------------------------------------------------------------- deliver reply
8 pending[c-42] found -> complete waiter; delete entryTimeline: the timeout and the orphan
requestor (deadline 2 s) replier (takes 3 s)
1 t=0.0 publish c-42, ttl=2000 ms ---->
2 t=0.1 starts work
3 t=2.0 deadline fires: delete pending[c-42]; return 504-ish error
4 t=3.0 publishes reply c-42 ---->
5 t=3.0 reply arrives; pending[c-42] missing -> drop (orphan)
-- the work was done for nobody; with a request TTL the broker would have discarded
-- the request at t=2.0 if the replier had not yet picked it upConcept catalogue
Request-Reply Must-know
In plain words: you send a message, and you get a second message back on a different road. There is no "return value"; there are two independent deliveries.
Common misunderstanding: "It is a function call over a queue." A local return value needs no independent network delivery. Request-reply adds several distinct failure windows: the request is lost, the replier is slow, the reply is lost, the reply is late, the reply is duplicated.
Definition: a requestor publishes a request message on a request channel and consumes a reply message from a reply channel. The request channel can be point-to-point or publish-subscribe; the reply ordinarily targets the individual requester (EIP, Request-Reply).
Real scenarios: a pricing service called through RabbitMQ by many web nodes; a license check between an on-premise agent and a SaaS backend where only the broker is reachable; a scatter-gather where one request fans out to several repliers and the requestor aggregates replies (the aggregator keeps the same id for all replies and counts them).
| Product | How request-reply is expressed |
|---|---|
| RabbitMQ | reply_to + correlation_id properties, default exchange routes by queue name, Direct Reply-To |
| Kafka | Headers by convention, a reply topic or partition; no broker feature |
| Redis Streams | Request stream + per-requester reply stream, or Pub/Sub channel |
| NATS | Client request helpers publish a unique reply subject (inbox) and await one answer with a timeout; newer clients can multiplex replies under one subject hierarchy |
| Pulsar | Convention again: a reply topic plus message properties |
| SQS | A response queue per client, or a temporary-queue helper library |
| Laravel queue | No reply channel: Job::dispatch() returns a PendingDispatch, not the queued job’s eventual result; the reply is a row, a cache key or a broadcast |
Correlation Identifier Must-know
In plain words: a ticket number. The requestor writes it on the request; the replier copies it onto the answer; the requestor matches the two.
Common misunderstanding: "I can use the message id from the broker." Not portable: Kafka offsets exist only after the append, and RabbitMQ assigns no id unless the publisher sets message_id. The requestor generates the id and owns it.
Definition: EIP lists six parts: requestor, replier, request, reply, request id, correlation id. The replier copies the request identifier into the response correlation field.
| Id type | Properties | Use |
|---|---|---|
| UUIDv4 / random 128-bit | Unique, unordered, safe | Default for correlation_id |
| ULID / UUIDv7 | Time-ordered | Easier to search logs and use as a status resource id (see ID generation) |
| Business key (order number) | Meaningful, may repeat | Never alone: two requests for the same order need two ids |
| Counter per client | Small | Needs a client id too; breaks on restart |
| Trace id | Spans many hops | Not a correlation id; see correlation across hops |
1 requestor: id = 7f3a...; pending[7f3a...] = waiter A
2 requestor: id = 91cc...; pending[91cc...] = waiter B
3 replier : gets 91cc... first (faster work), replies correlation_id=91cc...
4 requestor: reply 91cc... -> waiter B (replies may arrive out of order)
5 replier : replies correlation_id=7f3a...
6 requestor: reply 7f3a... -> waiter AThe out-of-order arrival in steps 3 to 6 is why you need the id at all: with one reply queue per client and several calls in flight, the queue order is not the request order.
Return Address and reply queue strategies Must-know
In plain words: the return address is the "send the answer here" line on an envelope. The only real design question is what "here" is.
Common misunderstanding: "The replier should know where requestors live." It should not. The requestor decides, so the replier needs no configuration and can serve any number of clients (EIP, Return Address places that routing knowledge with the requestor).
Definition: the request message carries a destination name; the replier publishes the reply to it.
| Strategy | Queue lifetime | Cost | Reply survives a requestor reconnect | Good for |
|---|---|---|---|---|
| One queue per request | Created and deleted per call | High: repeated queue declaration/deletion costs metadata work; clusters add coordination | No | Never at volume |
| One exclusive, auto-delete queue per client (tutorial 6) | Lives as long as the connection | Low: one declare at startup | No: deleted on disconnect | Short calls, many clients |
| One long-lived named queue per client or per service | Survives restarts (durable, not exclusive) | Low, but you manage cleanup | Yes | Long-running tasks where replies must wait |
| One shared reply queue for all clients | One | Lowest | Yes | Consumers compete: only one receives each reply. Use a dispatcher with shared pending state or route to per-requester queues; a client-side filter alone loses other clients’ answers |
| Direct Reply-To pseudo-queue | None | Lowest: no metadata, no process | No: at-most-once | Tens of thousands of clients, replies you can lose |
RabbitMQ documents these lifetime trade-offs: an exclusive queue belongs to one live connection, while a durable non-exclusive queue can buffer across reconnects. The requester must also persist enough correlation state to use a recovered reply; queue durability alone does not recover its in-memory pending table.
RabbitMQ queue arguments that matter for a reply queue.
| Argument or flag | Effect on a reply queue |
|---|---|
exclusive=true | Only the declaring connection can use it; deleted when that connection closes |
auto-delete=true | Deleted when the last consumer cancels |
durable=false | Queue is not recovered after a broker restart (fine for a reply queue) |
| Server-named (empty name) | The broker generates amq.gen-...; the client reads it from queue.declare-ok and puts it in reply_to |
x-expires | Queue is deleted after N ms of disuse: protects long-lived queues from leaking |
x-message-ttl | Replies older than N ms vanish; matches the caller's deadline |
| Client-named | Well-known name such as client-7.replies; needs a naming scheme and a cleanup policy |
Direct Reply-To Important
In plain words: RabbitMQ lets the requester say "reply to the special name amq.rabbitmq.reply-to", and the broker delivers the reply straight to that requester's channel without ever creating a queue.
Common misunderstanding: "It is a normal queue with a special name." The name behaves like a destination in the protocol but has no ordinary queue resource to list or delete.
Definition (AMQP 0-9-1). From the RabbitMQ docs:
- The requester consumes from the pseudo-queue
amq.rabbitmq.reply-toin no-ack mode; there is no need to declare it. - The request sets
reply-totoamq.rabbitmq.reply-to. - RabbitMQ rewrites the reply address to a generated
amq.rabbitmq.reply-to.destination with an opaque suffix. - The responder publishes the reply to the default exchange with that value as routing key.
1 requester: channel.consume("amq.rabbitmq.reply-to", no_ack=true) same channel as step 2
2 requester: publish(rk="quotes.rpc", reply_to="amq.rabbitmq.reply-to", correlation_id=c-42)
3 broker : rewrites reply_to -> "amq.rabbitmq.reply-to.g1h2AA..." opaque suffix
4 responder: receives request, reads reply_to, does the work
5 responder: publish(exchange="", rk="amq.rabbitmq.reply-to.g1h2AA...", correlation_id=c-42)
6 broker : delivers to the requester's channel process directly no queue buffers it
7 requester: deliver reply; match c-42Limits (documented, version 4.4 page):
| Limit | Meaning |
|---|---|
| Requester must consume in automatic-ack mode | There is no queue to return a rejected or unacked reply to |
| Same connection and channel for consume and publish | Consuming on another channel does not work |
| At most one Direct Reply-To consumer per channel | Plan one consumer, many in-flight requests |
| At-most-once; dropped if the requester disconnects | Reconnect; retry only when the operation is idempotent or deduplicated |
| Not durable, not replicated, not buffered | A reply to a slow requester is dropped, not queued |
With the mandatory flag the name is treated as routable | The broker will not send basic.return even if the requester is gone |
Not visible in the management UI or list_queues | Visible only in Prometheus under queue_type="rabbit_volatile_queue" |
| Not for hundreds of replies per second to the same requester | Use a real queue to buffer a requester that cannot keep up |
| Works for AMQP 1.0 as well, and across protocols | AMQP 1.0 needs snd-settle-mode settled, expiry-policy link-detach, capability rabbitmq:volatile-queue |
Checking whether the requester is still there (expensive replies). AMQP 0-9-1: passively declare the generated reply name on a disposable channel; it either succeeds (0 ready, 1 consumer) or fails. AMQP 1.0: an HTTP GET over AMQP returns 200 while the requester is connected.
Which metric tells you replies are dropped: rabbitmq_global_messages_dead_lettered_maxlen_total{queue_type="rabbit_volatile_queue",dead_letter_strategy="disabled"} counts direct replies dropped by RabbitMQ.
| Choose Direct Reply-To when | Avoid it when |
|---|---|
| Many (tens of thousands) clients, short calls | Losing a reply is unacceptable |
| High connection churn: connect, one RPC, disconnect | Replies must be buffered while the client reconnects |
| A missing reply can be retried safely using a stable logical idempotency key | Many replies per second go to one requester |
| You want no queue metadata in the metadata store | Long-running tasks needing retained replies |
Timeouts and orphaned replies Must-know
In plain words: every call needs a "give up" time, and every reply that arrives after it is trash that must be recognised and thrown away.
Common misunderstanding: "If the caller times out, the work is cancelled." Nothing cancels the work. The replier may still run it, and a retried request may run it a second time.
Definition: an orphan is a reply whose id is not in the pending table. For this transient pending-table design, unknown correlation ids are ignored; durable workflows instead reconcile them against persisted state.
| Layer | Setting | What it bounds |
|---|---|---|
| Caller | context.WithTimeout (Go), Http::timeout() or a loop deadline (PHP) | How long this call waits |
| Request message | expiration (per-message TTL) on the publish, or x-message-ttl on the queue | How long the request may sit before a worker gets it |
| Replier | An explicit absolute deadline header plus bounded local work time and clock-skew allowance; queue TTL alone cannot reveal elapsed transit time | Work done for nobody |
| Reply | x-message-ttl / x-expires on a long-lived reply queue; EXPIRE on a Redis reply stream; topic retention.ms on Kafka | Orphans piling up |
| Connection | Heartbeats, TCP keepalive, bounded transport writes | Dead peers and stuck socket writes; context cancellation alone may not interrupt publishing |
Set the request TTL equal to or slightly below the caller's timeout. A request that has expired while queued is dropped (or dead-lettered, if the queue has a dead-letter exchange), so a backed-up queue sheds stale work instead of serving it.
1 t=0 caller timeout 2 s; request expiration 2000 ms
2 t=0..2 queue backed up: worker busy with older requests
3 t=2.0 caller gives up: pending entry removed
4 t=2.0 request TTL expires in the queue -> dropped (or dead-lettered)
5 t=2.5 worker would have reached it: nothing to do, no orphan replyConsumer cancel on client death. When a requester dies, its exclusive reply queue is deleted with its connection. A replier that publishes to a queue name that no longer exists, through the default exchange, loses the message silently unless it publishes with mandatory=true and listens for basic.return (Go: Channel.NotifyReturn). On the requester side a consumer can also be cancelled by the broker (for example when its queue is deleted or its node fails): amqp091-go closes the deliveries channel, and a correct client fails all pending waiters at that moment instead of letting each one wait out its deadline (Go snippet).
Duplicate replies and idempotency Important
In plain words: you can get the answer twice, and you can ask the question twice. Both must be harmless.
Common misunderstanding: "Exactly-once request-reply is a broker feature." It is an application property: an idempotent replier plus a requestor that ignores ids it has already completed. See delivery guarantees.
Definition: a reply publish and request acknowledgment are separate operations. A crash between them can redeliver the request after the requester already received its answer. The requester completes once; the replier must keep side effects idempotent independently.
1 replier: receives request c-42, does the work, publishes reply c-42
2 replier: crashes before ack
3 broker : redelivers c-42 to another replier (the first one never acked)
4 replier2: does the work again, publishes reply c-42
5 requestor: first reply completes waiter and deletes the entry
6 requestor: second reply has an unknown id -> dropped
-- the effect (a charge, an email) happened twice unless the work is idempotent| Where the duplicate arises | Defence |
|---|---|
| Duplicate reply to the requestor | Delete the pending entry on the first reply; ignore the second |
| Duplicate request to the replier | Dedup on request id: inbox table, unique constraint, or natural idempotency (PUT semantics) |
| Client retry after timeout | Same business idempotency key on every attempt; HTTP Idempotency-Key header (IETF draft draft-ietf-httpapi-idempotency-key-header, still an Internet-Draft) |
| Webhook delivered twice | Receiver dedups on the event id or Idempotency-Key |
-- Replier-side dedup: one row per request id, same transaction as the effect.
CREATE TABLE processed_requests (
request_id uuid PRIMARY KEY,
reply_body jsonb NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
-- On receipt: if the insert conflicts, republish the stored reply instead of redoing the work.
INSERT INTO processed_requests (request_id, reply_body)
VALUES ($1, $2)
ON CONFLICT (request_id) DO NOTHING
RETURNING request_id;Stripe documents the same idea for HTTP: "retries with the same key return the saved response" (API v1; v2 behaves differently), the key is generated by the client, and v1 keys may be pruned after 24 hours (Stripe, idempotent requests). RFC 9110 gives the baseline: only idempotent methods may be retried automatically ("PUT, DELETE, and safe request methods are idempotent"); a non-idempotent POST needs an implemented deduplication contract; a header alone does not create one.
Sync over async Must-know
In plain words: a web request starts, publishes a message, and then stands there holding a worker until the answer shows up. It looks asynchronous in the architecture diagram and behaves exactly like a slow function call.
Common misunderstanding: "The broker will smooth out the load." It does smooth the load on the replier. It does not smooth the load on the callers, because the callers wait. The buffer that a queue provides is useless if nobody can afford to wait for it to drain.
Definition: an anti-pattern in which a request handler publishes a message and blocks, polls or sleeps until a reply (or a status change) arrives. The handler's thread, process or connection is tied up for the replier's latency.
Why it fails.
| Resource tied up while waiting | Typical limit | Symptom when exhausted |
|---|---|---|
PHP-FPM worker (pm.max_children) | Tens | 502/504 from the proxy; even /health stalls |
| Thread in a Java servlet pool | Hundreds | Request queue in the container |
| Go goroutine | Millions, but each holds a connection, a map entry, a request context | Memory growth, file descriptors, reply-table size |
| Node.js event loop | One thread, many promises | Latency rises; timers fire late; memory |
| Database connection held in an open transaction while waiting | max_connections, pool size | "too many connections" (see connection pooling) |
| Reverse proxy (nginx, ALB) timeout | 30-60 s | 504 Gateway Timeout, caller retries, load doubles |
1 8 web workers; one back-end worker does 20 jobs/s (50 ms each)
2 offered load 100 requests/s -> every web worker blocks on a reply
3 8 of 8 workers busy; new requests wait for a slot (503 or proxy 504)
4 /health also needs a worker -> the load balancer marks the node dead
5 callers time out and retry -> offered load rises (retry storm)
6 queue keeps the old jobs: the back-end now works for callers that leftThe lab models offered load above backend capacity; all outcomes below are expected, not run in this authoring pass.
What to do instead.
| Instead of | Do | Why |
|---|---|---|
| Block for the reply | Return 202 + status resource (next section) | Releases the worker in milliseconds |
Poll in the handler (while + sleep) | Client polls the status resource; or push via SSE/WebSocket | Polling moves to the client, which can be many |
| Broker RPC for a read | REST or gRPC with a deadline | One hop; failure visible immediately |
| Broker RPC for a command that must not be lost | Command message + reply event, correlated by id | Nothing waits |
| An unbounded wait | A bounded one: deadline, TTL, bulkhead (separate worker pool for RPC callers), circuit breaker | Fail fast and keep the rest of the app alive |
When sync over async is acceptable: low volume, internal tool, hard deadline of a few seconds, a pool of workers reserved for it (a bulkhead), and a clear reason the replier must sit behind a broker. Anything else is a design smell.
202 and a status resource Must-know
In plain words: the server says "I have your request, here is the address where you can check on it", and hangs up.
Common misunderstanding: "202 means it will succeed." RFC 9110 explicitly allows accepted work to remain unprocessed or fail later. The status resource must be able to say failed.
Definition: POST /quotes returns 202 Accepted, a Location header pointing at /quotes/{id}, and a body describing the current state. The worker updates the row; the client polls (honouring Retry-After) or is pushed the result.
| State | HTTP on the status resource | Meaning |
|---|---|---|
queued / running | 200 with state and optionally Retry-After | Not finished |
done | 200 with the result, or 303 See Other to the result resource | Finished successfully |
failed | 200 with state=failed and an error object | The work ended in error |
expired | 410 Gone | Result deleted after retention |
| unknown id | 404 | Never existed |
| cancel requested | DELETE /quotes/{id} returns 202 or 204 | Cancellation is itself asynchronous |
1 client : POST /quotes {sku:A-1} Idempotency-Key: k-9
2 server : INSERT quote(state=queued); publish job after commit
3 server : 202 Accepted, Location: /quotes/q-1, Retry-After: 1
4 worker : consumes job, writes price, state=done
5 client : GET /quotes/q-1 -> 200 {state:running}
6 client : GET /quotes/q-1 -> 200 {state:done, price:4200}-- The status resource is a row. The id is the correlation id.
CREATE TABLE quotes (
id uuid PRIMARY KEY,
sku text NOT NULL,
state text NOT NULL CHECK (state IN ('queued','running','done','failed')),
price_cents integer,
error text,
updated_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX quotes_state_updated_idx ON quotes (state, updated_at); -- for reconciliation sweepsReconciliation. A queued job can be lost (broker flushed, bug). A periodic sweep (state IN ('queued','running') AND updated_at < now() - interval '15 minutes') republishes or fails them: see durable workflows & jobs and the outbox for publishing in the same transaction as the insert.
Asynchronous reply to a client: webhook, SSE, WebSocket Important
In plain words: instead of the caller asking "are you done?" every second, the server tells the caller when it is done.
Common misunderstanding: "WebSocket is the modern way and SSE is legacy." SSE is simpler for one-way server-to-browser updates and reconnects automatically; WebSocket is for two-way traffic.
| Mechanism | Direction | Best for | Cost and catch |
|---|---|---|---|
| Client polling of the status resource | Client to server | Simplest; works through any proxy | Latency equal to the poll interval; load grows with clients; use Retry-After and backoff |
| Long polling | Client to server, held open | Older infrastructure | Holds a connection; a milder form of sync over async |
Server-Sent Events (SSE, text/event-stream) | Server to browser | Result and progress for one page | One long-lived HTTP connection per viewer; auto-reconnect; proxies must not buffer |
| WebSocket | Both ways | Interactive apps, many events | Own protocol; sticky routing or a pub/sub backplane (Redis) behind several nodes |
| Webhook / callback URL | Server to another server | B2B integrations | Receiver must be reachable; sender retries; receiver dedups; sign the payload |
| Message to a reply queue / reply event | Service to service | Internal flows | Requires the caller to be a messaging participant |
| Mobile push, email | Server to a person | The user left | Not a data channel |
In Laravel the event is broadcast over Reverb (WebSocket), Pusher or Ably, or on a Mercure hub; see Laravel. In Go, SSE needs only net/http and a Flusher (snippet).
1 browser: POST /quotes -> 202 Location: /quotes/q-1
2 browser: opens EventSource("/quotes/q-1/events") or subscribes to private channel quotes.q-1
3 worker : finishes; publishes "quote.ready" to the hub (Redis / broker)
4 web node holding the stream: writes "event: quote.ready"
5 browser: renders; closes the stream
6 (if the worker finished before step 2: the browser GETs /quotes/q-1 on connect and sees done)Step 6 is the part people miss. A push channel is at-most-once to whoever is connected at that moment. The status resource is the source of truth; the push is an optimisation. Establish the subscription first, then fetch durable status, and reconcile after reconnects or missed heartbeats. Fetch-then-subscribe has a race: completion can happen between the two. Version the status to ignore stale or duplicate push notifications.
Correlation across hops: traceparent versus correlation_id Important
In plain words: the correlation id says "this answer matches that question". The trace id says "all of these messages belong to one user action". They are different questions and need different ids.
Common misunderstanding: "The correlation id is my trace id, I will log it everywhere." A correlation id lives for one request-reply pair. A trace spans many pairs and hops, and the tracing backend needs the W3C format to stitch spans together.
Definition: W3C Trace Context defines traceparent ("describes the position of the incoming request in its trace graph in a portable, fixed-length format") and tracestate for vendor data. Example from the spec: traceparent: 00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01, four fields: version, trace-id, parent-id, trace-flags. Use the tracing SDK to validate and propagate incoming context under the service’s trust policy; invalid all-zero trace/span ids must not be continued. See messaging observability.
| Id | Scope | Created by | Changes per hop? | Used for |
|---|---|---|---|---|
correlation_id | One request-reply pair | Requestor | No: copied from request to reply | Matching a reply to a waiter |
message_id | One message | Publisher | Yes: every message has its own | Deduplication, logs |
traceparent trace-id | One user action across all services | First service in the chain | No | Joining spans in Jaeger, Tempo, Zipkin |
traceparent parent-id | One span | Each service when it makes a child call | Yes | Building the tree |
causation_id (convention) | "Which message caused this one" | Publisher | Yes | Reconstructing event chains |
| Business id (order id) | One aggregate | Domain | No | Searching by domain object |
1 browser -> api : traceparent 00-T-s1-01 trace T
2 api -> broker : request, correlation_id=c-42, traceparent 00-T-s2-01 child span s2
3 broker -> pricing: consumer extracts traceparent, starts span s3 (parent s2)
4 pricing -> broker: reply, correlation_id=c-42 (copied), traceparent 00-T-s3-01
5 broker -> api : reply matched by c-42; span s2 ends; trace T continuesRules: use the transport’s metadata convention; copy correlation_id into its reply; create a new span id when starting a child span and let instrumentation propagate it. Preserve valid tracestate when continuing a trace, and discard it when rejecting invalid context. Log correlation and trace ids without sensitive payloads. The Go snippet after/correlation builds exactly these headers.
Kafka request-reply pitfalls Important
In plain words: Kafka is a shared log, not a mailbox. Nothing in it says "this record is for client 7 only", so you build mailboxes yourself, and they are clumsy.
Common misunderstanding: "Kafka can do everything RabbitMQ does, so request-reply is the same." Kafka has no per-client queue, no reply-to property and no per-message TTL. Spring for Apache Kafka ships ReplyingKafkaTemplate, which shows the shape of the workaround: the Spring docs list KafkaHeaders.CORRELATION_ID, REPLY_TOPIC and REPLY_PARTITION as its headers and a default reply timeout of 5 seconds.
| Pitfall | Why | Mitigation |
|---|---|---|
| No per-client queue | Replies go to a shared topic whose groups/assignment determine readership | One shared reply topic with a unique group.id per instance (every instance reads every reply and ignores most; each independent group reads every reply and its client filters correlation ids), or one partition per instance, or one topic per instance |
| Topic per client | Topic creation is a metadata operation; thousands of ephemeral topics strain the controller | Avoid for short-lived clients |
| Consumer group rebalances | Joining or leaving a group triggers a rebalance; a new requester may wait seconds before it can receive | Manual partition assignment, no group management (kgo.ConsumePartitions), or group.instance.id static membership for stable instances |
| Starting position | A new consumer with auto.offset.reset=latest may miss a reply produced before its first poll | Wait for assignment before sending the first request (Spring has waitForAssignment) |
| Ordering | A topic is ordered per partition only; the replier's output partition is not the request's | Do not rely on ordering for replies; correlate by id (ordering & partitioning) |
| Retention | Replies are kept for retention.ms, not dropped on disconnect | Short retention on the reply topic (minutes) so orphans cost little |
| Latency | Producer batching (linger.ms), fetch waits, group coordination | Tune for latency at the cost of throughput |
| Partition cost | Partitions are not free; one per requester does not scale | Cap requesters per reply topic, or hash requester id to a partition and filter |
| Duplicates | At-least-once; transactions only cover Kafka-to-Kafka | Idempotent replier; stable logical operation key across caller retries, separate correlation id per attempt |
| Timeouts | No built-in; the requestor owns the timer | A context deadline and a deadline header |
When Kafka request-reply is justified: Kafka is already the only inter-service transport (a platform rule), the call is a command with a tolerable multi-second latency, and the reply is itself an event others may use (an audit trail of answers). For sub-second query-like calls, use REST or gRPC. Kafka orders each partition and assigns it to one member within a consumer group; that is different from delivery to a named requester.
Redis Streams and Pub/Sub replies Good to know
In plain words: Redis gives you two cheap mailboxes. Pub/Sub is a shout across the room (gone if nobody is listening). A stream is a notebook (kept until trimmed).
Common misunderstanding: "Pub/Sub is fine for a reply because replies are short-lived." Redis documents at-most-once Pub/Sub delivery without replay. A reply published before the requester subscribed is gone.
| Option | Mechanism | Strength | Weakness |
|---|---|---|---|
| Pub/Sub channel per request | SUBSCRIBE reply:{id} before XADD of the request; replier PUBLISHes | Lowest latency, no cleanup | At-most-once; subscribe-first race; a subscription per waiter or a pattern subscribe |
| Reply stream per requester | Request carries reply_to = stream name; replier XADDs the reply; requester XREAD BLOCK from its last id | Durable, replayable, inspectable | Needs EXPIRE on the whole key and trimming; blocking reads hold a connection |
| Shared reply stream, one consumer group | Group members divide deliveries | One shared destination | Wrong owner may receive a reply; use a dispatcher, per-requester groups, independent XREAD cursors, or private reply streams |
| None of these | Use REST | The honest answer for most cases |
A subtle point for the stream option: tail by last-seen entry id, not by $. $ means "only entries added after this call starts", so entries written between two blocking reads are missed.
Messaging versus REST and gRPC Must-know
In plain words: REST and gRPC are "call and wait". Messaging is "hand over and carry on". Pick by whether the caller can carry on.
Common misunderstanding: "gRPC is more modern, so it is a messaging alternative." gRPC is a typed RPC framework on HTTP/2 with streaming and deadlines; every property of a synchronous call (availability multiplies, latency adds) still applies. Its deadline propagation is a good idea to copy into your own timeouts.
| Dimension | REST / gRPC (synchronous) | Messaging with a reply | Messaging, no reply (command or event) |
|---|---|---|---|
| Latency | One network round trip; low and predictable | Two broker hops plus replier queueing; higher and variable | Not on the caller's path |
| Temporal coupling | Both sides up at once | Both sides up within the timeout | None |
| Failure visibility | Immediate error | Timeout after the full deadline | Delayed (DLQ, monitoring) |
| Retries | Caller's job; needs idempotency keys | Broker redelivers requests; caller may also retry | Broker retries; see retry & backoff |
| Load balancing | Load balancer, service mesh | Competing consumers, built in | Built in |
| Backpressure | Rejects (429, 503) or queues in the proxy | Queue grows; caller times out | Queue grows; callers unaffected |
| Visibility / debugging | Request logs, traces, curl | Needs broker tooling and correlation ids | Same |
| Consistency | A remote call is not atomic with the caller’s database transaction | Publish and update do not commit together (see outbox) | Same |
| Ordering | Concurrent requests can finish out of order | Per queue or partition | Per queue or partition |
| Discovery and security | DNS, mTLS, gateway | Broker credentials, vhosts, ACLs | Same |
| Typical failure of the pattern | Cascading timeouts | Orphans, starvation, duplicate replies | Poison messages |
Rule of thumb from this table: if the caller must wait, the simpler transport wins; if the caller need not wait, do not make it.
What each product really does
| Capability | RabbitMQ | Kafka | Redis Streams / Pub/Sub | Laravel queue (database, redis, SQS, RabbitMQ package) |
|---|---|---|---|---|
| Return address primitive | reply_to property | Header by convention | Field by convention | None; row, cache key or broadcast |
| Correlation primitive | correlation_id property | Header by convention | Field by convention | The package copies the job payload id into correlation_id; no reply semantics |
| Per-client reply destination | Exclusive queue, long-lived queue, or Direct Reply-To | Partition or topic you create | Stream or channel you create | n/a |
| Zero-queue reply | Direct Reply-To (amq.rabbitmq.reply-to) | No | Pub/Sub channel (no storage) | n/a |
| Per-message TTL for requests | expiration property, x-message-ttl | No per-message TTL; topic retention.ms | No; MINID trimming or your own deadline field | Job retryUntil, #[Timeout] |
| Reply buffering while requester is away | Yes, in a classic or quorum reply queue; no with Direct Reply-To | Yes (log), until retention | Stream yes; Pub/Sub no | n/a |
| Detect a vanished requester | mandatory + basic.return (not for Direct Reply-To); passive declare | Not possible | Not possible; check EXISTS on the reply key | n/a |
| Competing replier instances | Several consumers on the request queue | Consumer group on the request topic | Consumer group on the request stream | Several queue:work processes |
| Latency class for one call | Low milliseconds | Higher: batching, fetch wait | Lowest | Poll interval or push depending on driver |
| Duplicate risk | Redelivery after missed ack | At-least-once, rebalance replays | Pending entry redelivery | Retries |
| Built-in RPC helper | Tutorial 6 clients; AMQP 1.0 Requester/Responder in the Java and .NET clients | Spring ReplyingKafkaTemplate | None | None |
Solutions: bounding, replacing and pushing
| Problem | Solution | How | Advantage | Cost or limitation |
|---|---|---|---|---|
| Caller waits forever | Deadline on every call | context.WithTimeout, Http::timeout, loop deadline | Fail fast | Needs a sensible number: p99 of the replier plus slack |
| Replier works for nobody | Request TTL | expiration / x-message-ttl; deadline header on Kafka and Redis | Stale work shed | Message may be dead-lettered; monitor |
| Orphan replies | Pending table, drop unknown ids | Delete entry on completion and on timeout | Trivial | Late replies are wasted bandwidth |
| Duplicate replies | Complete once | Delete on first reply | Trivial | Does not stop duplicate side effects |
| Duplicate side effects | Idempotent replier | Unique request id, processed_requests table, PUT semantics | Safe retries | Storage and a transaction |
| Reply queue sprawl | Per-client queue or Direct Reply-To | One consumer, many ids | No per-call declare | Direct Reply-To is at-most-once |
| Client died | Fail waiters when the consumer ends; mandatory for ordinary reply queues | NotifyReturn, closed deliveries channel | Fail local waiters promptly | No Direct Reply-To presence guarantee; Kafka needs application lifecycle handling |
| Web workers exhausted | 202 + status resource | Queue the job, return at once | Frees the worker | Client must poll or be pushed |
| User wants live result | SSE, WebSocket (Reverb), webhook | Event on completion | No polling | Backplane; at-most-once push |
| Need an answer now | REST or gRPC | Deadline, retries, idempotency key | Simplest | Both sides up at once |
| Caller cannot afford to lose a command | Command message, reply as event | Outbox on the sender | Durable | Eventual, not immediate |
| Hot reply queue | Competing consumers on replies are wrong | One reply queue per client | Natural ordering per client | More queues; use Direct Reply-To for churn |
| Trace broken at the broker | Propagate traceparent in headers | Inject on publish, extract on consume | One trace for the user action | Needs middleware in each service |
| Retry storm after a timeout | Backoff with jitter, retry budget, circuit breaker | See retry & backoff | Bounded amplification | Tuning |
Choosing: decision tables
By situation.
| Situation | Recommended | Extra technique | Reason |
|---|---|---|---|
| Web page needs a price or a permission now | REST or gRPC | Deadline, cache, circuit breaker | Fast read; failure should surface at once |
| User uploads a file, report takes a minute | 202 + status + SSE or poll | Reconciliation sweep | Never hold a web worker for a minute |
| Service A tells service B to start a process | Command message | Outbox, idempotent consumer | Temporal decoupling |
| Service A needs B's confirmation before continuing a saga | Command + reply event or saga step | Saga, timeout transition | The saga owns the waiting, not a thread |
| Thousands of IoT or edge clients need an answer | RabbitMQ Direct Reply-To | Request TTL, retry on timeout | No queue per client |
| Replies must survive reconnects | Durable named reply queue | x-expires, x-message-ttl | Broker buffers |
| Only Kafka is allowed between teams | Reply topic or partition, with deadline | Short retention.ms, manual assignment | Works; accept the latency |
| Redis is the only broker, replies are cheap | Pub/Sub for the reply, stream for the request | Subscribe first | Simple, lossy |
| Browser needs live status | SSE or Reverb WebSocket | Subscribe, then read status; reconcile on reconnect | Push plus source of truth |
| Third party must be told | Webhook | Signature, retries, Idempotency-Key | Standard B2B shape |
| Broadcast one request to many repliers, collect replies | Scatter-gather | Same id, counter, deadline | Aggregator pattern |
| Inside one process | A function call | None | Do not add a broker for a method call |
By latency budget (classes, not numbers).
| Budget for the whole call | Fits | Does not fit |
|---|---|---|
| Under a few milliseconds | In-process call | Any network hop |
| Tens of milliseconds | REST or gRPC in one region | Broker RPC with a cold queue |
| Hundreds of milliseconds to seconds | REST, gRPC, RabbitMQ RPC with a hot consumer | Kafka RPC without tuning |
| Seconds to minutes | 202 + status, async reply | Any blocking call |
| Hours | Workflow engine, email, webhook | Everything blocking |
By coupling and ownership.
| Question | If yes | If no |
|---|---|---|
| Do both teams want the same contract and release cadence? | REST or gRPC with a schema | Messaging with a versioned schema (schema evolution) |
| Must the callee be allowed to be down? | Messaging | REST with retries |
| Does one answer feed one decision? | Request-reply | Event, let consumers decide |
| Do you need the broker's routing or load balancing anyway? | Broker RPC may be acceptable | REST behind a load balancer |
Go
Before
An HTTP handler publishes a request and waits on a channel for the reply, with a hand-rolled id and no timeout. If the worker is down, the reply is lost, or the client disconnects, the goroutine and its map entry stay forever.
// Package main shows "sync over async": an HTTP handler that publishes a
// request message and then blocks until some other goroutine delivers the
// reply. It compiles and works on a good day; it has no timeout.
package main
import (
"fmt"
"net/http"
"sync"
)
// Bus is whatever publishes the request message (RabbitMQ, Kafka, ...).
type Bus interface {
Publish(correlationID string, body []byte) error
}
var (
mu sync.Mutex
pending = map[string]chan []byte{} // correlation id -> waiting handler
nextID int
)
// onReply is called by the reply consumer for every reply message.
func onReply(correlationID string, body []byte) {
mu.Lock()
ch := pending[correlationID]
delete(pending, correlationID)
mu.Unlock()
if ch != nil {
ch <- body // blocks forever if the handler already left
}
}
func quoteHandler(bus Bus) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
nextID++
id := fmt.Sprintf("req-%d", nextID) // fine until you run two instances
ch := make(chan []byte)
pending[id] = ch
mu.Unlock()
if err := bus.Publish(id, []byte(r.URL.Query().Get("sku"))); err != nil {
http.Error(w, err.Error(), http.StatusBadGateway)
return
}
// No timeout, no r.Context(): if the worker is down or the reply is
// lost, this goroutine, its map entry and the client connection stay
// stuck until the server is restarted.
body := <-ch
_, _ = w.Write(body)
}
}
func main() {
http.Handle("/quote", quoteHandler(nil))
_ = http.ListenAndServe(":8080", nil)
}After
If the caller really needs a reply, make the broker part explicit and bounded. RabbitMQ with Direct Reply-To: one no-ack consumer on amq.rabbitmq.reply-to, a UUID correlation id, a pending table, a context deadline, a queue TTL derived from it, an execution-deadline header, bounded in-flight calls and a rule that when the reply consumer ends every waiter is failed. Late replies find no entry and are dropped.
// Package main is a RabbitMQ RPC client using Direct Reply-To and a context
// timeout. One consumer on one channel serves every concurrent call.
package main
import (
"context"
"errors"
"fmt"
"log"
"net"
"os"
"strconv"
"sync"
"time"
"github.com/google/uuid"
amqp "github.com/rabbitmq/amqp091-go"
)
const directReplyTo = "amq.rabbitmq.reply-to"
type Client struct {
ch *amqp.Channel
queue string
mu sync.Mutex
pending map[string]chan result
closed bool
}
type result struct {
body []byte
err error
}
// ErrReplyChannelLost is returned to every waiter when the reply consumer
// ends (channel or connection closed, consumer cancelled). Direct Reply-To
// replies are at-most-once. Retry only idempotent or deduplicated operations.
var ErrReplyChannelLost = errors.New("reply consumer closed; outcome may be unknown")
// NewClient consumes from the pseudo-queue in no-ack mode. The same channel
// must be used to publish requests (RabbitMQ Direct Reply-To rule).
func NewClient(ch *amqp.Channel, requestQueue string) (*Client, error) {
replies, err := ch.Consume(directReplyTo, "", true, false, false, false, nil)
if err != nil {
return nil, fmt.Errorf("consume reply-to: %w", err)
}
c := &Client{ch: ch, queue: requestQueue, pending: map[string]chan result{}}
go func() {
for d := range replies {
c.mu.Lock()
w, ok := c.pending[d.CorrelationId]
delete(c.pending, d.CorrelationId)
c.mu.Unlock()
if !ok {
continue // late or duplicate reply: nobody is waiting, drop it
}
w <- result{body: d.Body} // buffered, never blocks
}
// The deliveries channel closed: fail everyone instead of letting
// them wait for their full deadline.
c.mu.Lock()
c.closed = true
for id, w := range c.pending {
w <- result{err: ErrReplyChannelLost}
delete(c.pending, id)
}
c.mu.Unlock()
}()
return c, nil
}
// Call publishes a request and waits for the reply or ctx.Done().
func (c *Client) Call(ctx context.Context, body []byte) ([]byte, error) {
if _, ok := ctx.Deadline(); !ok {
return nil, errors.New("RPC requires a deadline")
}
if err := ctx.Err(); err != nil {
return nil, err
}
deadline, _ := ctx.Deadline()
id := uuid.NewString()
wait := make(chan result, 1)
c.mu.Lock()
if c.closed {
c.mu.Unlock()
return nil, ErrReplyChannelLost
}
if len(c.pending) >= 256 {
c.mu.Unlock()
return nil, errors.New("RPC in-flight limit reached")
}
c.pending[id] = wait
c.mu.Unlock()
defer func() {
c.mu.Lock()
delete(c.pending, id) // timed out: later replies become orphans
c.mu.Unlock()
}()
err := c.ch.PublishWithContext(ctx, "", c.queue, false, false, amqp.Publishing{
ContentType: "application/json",
CorrelationId: id,
ReplyTo: directReplyTo,
Expiration: strconv.FormatInt(max(1, time.Until(deadline).Milliseconds()), 10), // queue residence only
Headers: amqp.Table{"deadline_unix_ms": strconv.FormatInt(deadline.UnixMilli(), 10)},
Body: body,
})
if err != nil {
return nil, err
}
select {
case res := <-wait:
return res.body, res.err
case <-ctx.Done():
return nil, ctx.Err()
}
}
func main() {
url := os.Getenv("AMQP_URL")
if url == "" {
log.Fatal("set AMQP_URL, e.g. amqp://guest:guest@localhost:5672/")
}
conn, err := amqp.DialConfig(url, amqp.Config{
Dial: func(network, address string) (net.Conn, error) {
c, err := net.DialTimeout(network, address, time.Second)
if err != nil {
return nil, err
}
return &boundedWriteConn{Conn: c}, nil
},
})
if err != nil {
log.Fatal(err)
}
defer conn.Close()
ch, err := conn.Channel()
if err != nil {
log.Fatal(err)
}
client, err := NewClient(ch, "quotes.rpc")
if err != nil {
log.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
reply, err := client.Call(ctx, []byte(`{"sku":"A-1"}`))
log.Printf("reply=%s err=%v", reply, err)
}
// Reply is the responder side: publish to the default exchange using the
// request's ReplyTo as the routing key, and copy the correlation id.
func Reply(ctx context.Context, ch *amqp.Channel, req amqp.Delivery, body []byte) error {
return ch.PublishWithContext(ctx, "", req.ReplyTo, false, false, amqp.Publishing{
CorrelationId: req.CorrelationId,
ContentType: "application/json",
Body: body,
})
}
// Context cancellation cannot interrupt an amqp091-go socket write. This
// connection-wide cap bounds each write; it is separate from the RPC deadline.
// Shared connections must not be closed just to cancel one individual call.
type boundedWriteConn struct{ net.Conn }
func (c *boundedWriteConn) Write(p []byte) (int, error) {
if err := c.Conn.SetWriteDeadline(time.Now().Add(time.Second)); err != nil {
return 0, err
}
return c.Conn.Write(p)
}The replier is a competing consumer with prefetch 1, a quorum request queue, a mandatory reply publish with NotifyReturn for ordinary queues, and an ack only after a publisher confirm. A confirm means broker acceptance, never requester receipt; Direct Reply-To may still drop the answer.
// Package main is the replier side of a RabbitMQ RPC: a competing consumer
// with prefetch 1, a per-request deadline, a mandatory reply publish so a
// vanished ordinary reply queue is noticed, and ack after broker confirmation.
// Direct Reply-To is considered routed even if its requester has disconnected.
package main
import (
"context"
"encoding/json"
"log"
"os"
"strconv"
"time"
amqp "github.com/rabbitmq/amqp091-go"
)
const requestQueue = "quotes.rpc"
type quoteRequest struct {
SKU string `json:"sku"`
}
func main() {
url := os.Getenv("AMQP_URL")
if url == "" {
log.Fatal("set AMQP_URL, e.g. amqp://guest:guest@localhost:5672/")
}
conn, err := amqp.Dial(url)
if err != nil {
log.Fatal(err)
}
defer conn.Close()
ch, err := conn.Channel()
if err != nil {
log.Fatal(err)
}
// Durable quorum queue for requests; replies never touch a queue we own.
if _, err := ch.QueueDeclare(requestQueue, true, false, false, false,
amqp.Table{amqp.QueueTypeArg: amqp.QueueTypeQuorum}); err != nil {
log.Fatal(err)
}
// One unacked request per worker: slow requests do not pile up in one process.
if err := ch.Qos(1, 0, false); err != nil {
log.Fatal(err)
}
if err := ch.Confirm(false); err != nil {
log.Fatal(err)
}
// Ordinary missing reply queues return basic.return. Direct Reply-To does not.
returns := ch.NotifyReturn(make(chan amqp.Return, 16))
go func() {
for r := range returns {
log.Printf("reply %s had no route (%d %s): requester is gone", r.CorrelationId, r.ReplyCode, r.ReplyText)
}
}()
deliveries, err := ch.Consume(requestQueue, "", false, false, false, false, nil)
if err != nil {
log.Fatal(err)
}
for d := range deliveries {
if err := handle(ch, d); err != nil {
log.Fatal(err)
}
}
}
func handle(ch *amqp.Channel, d amqp.Delivery) error {
if d.ReplyTo == "" || d.CorrelationId == "" {
// Reject: dead-letter only with a configured DLX; otherwise discard.
return d.Reject(false)
}
deadline := time.Now().Add(3 * time.Second)
if raw, ok := d.Headers["deadline_unix_ms"].(string); ok {
ms, err := strconv.ParseInt(raw, 10, 64)
if err != nil {
return d.Reject(false)
}
requested := time.UnixMilli(ms)
if requested.Before(deadline) {
deadline = requested
}
}
if !deadline.After(time.Now()) {
return d.Reject(false)
}
// Production requires monitored clock skew; queue TTL is not an execution timer.
ctx, cancel := context.WithDeadline(context.Background(), deadline)
defer cancel()
var req quoteRequest
if err := json.Unmarshal(d.Body, &req); err != nil {
return d.Reject(false)
}
body, _ := json.Marshal(map[string]any{"sku": req.SKU, "price_cents": 1999})
// mandatory detects missing ordinary queues, not vanished Direct Reply-To clients.
confirmation, err := ch.PublishWithDeferredConfirmWithContext(ctx, "", d.ReplyTo, true, false, amqp.Publishing{
ContentType: "application/json",
CorrelationId: d.CorrelationId, // copy the request id into the reply
Body: body,
})
if err != nil {
return d.Nack(false, true) // unknown publication outcome; dedup is required
}
confirmed, err := confirmation.WaitContext(ctx)
if err != nil || !confirmed {
return d.Nack(false, true)
}
return d.Ack(false) // broker accepted reply; requester receipt is still NOT guaranteed
}The lightweight trace example is illustrative; use a tracing SDK in production to preserve valid tracestate, enforce trust policy and create spans correctly.
The headers that cross every hop: the business correlation_id copied unchanged and a W3C traceparent whose parent id is replaced at each hop.
// Package main shows what travels with a request across hops: a business
// correlation id (one per request-reply pair) and a W3C traceparent (one per
// distributed trace). They answer different questions and both go in headers.
package main
import (
"crypto/rand"
"encoding/hex"
"fmt"
"regexp"
"strings"
amqp "github.com/rabbitmq/amqp091-go"
)
var traceparentRE = regexp.MustCompile(`^00-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$`)
func randHex(n int) string {
b := make([]byte, n)
_, _ = rand.Read(b)
return hex.EncodeToString(b)
}
// childTraceparent keeps the trace id and swaps in a new parent id, which is
// what a service does before it calls the next hop (W3C Trace Context).
func childTraceparent(parent string) string {
m := traceparentRE.FindStringSubmatch(parent)
if m == nil || m[1] == strings.Repeat("0", 32) || m[2] == strings.Repeat("0", 16) {
return "00-" + randHex(16) + "-" + randHex(8) + "-01" // start a new trace
}
return "00-" + m[1] + "-" + randHex(8) + "-" + m[3]
}
// Request builds an AMQP publishing for the request leg. CorrelationId matches
// reply to request; traceparent lets the tracing backend join the hops.
func Request(traceparent, replyTo string, body []byte) amqp.Publishing {
return amqp.Publishing{
ContentType: "application/json",
CorrelationId: randHex(16),
ReplyTo: replyTo,
MessageId: randHex(16), // identifies this message; useful for dedup
Headers: amqp.Table{"traceparent": childTraceparent(traceparent)},
Body: body,
}
}
// Reply copies the correlation id and continues the same trace.
func Reply(req amqp.Delivery, body []byte) amqp.Publishing {
tp, _ := req.Headers["traceparent"].(string)
return amqp.Publishing{
ContentType: "application/json",
CorrelationId: req.CorrelationId,
Headers: amqp.Table{"traceparent": childTraceparent(tp)},
Body: body,
}
}
func main() {
in := "00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01" // example from the W3C spec
req := Request(in, "amq.rabbitmq.reply-to", []byte(`{}`))
fmt.Println("correlation_id:", req.CorrelationId)
fmt.Println("traceparent :", req.Headers["traceparent"])
}If the caller does not need the answer now, do not wait: POST returns 202 with a Location header, a worker updates the status row, and the client polls.
The executable local publisher is an in-memory teaching substitute: process exit loses queued work. Missing publishers return 503; publish failure marks local status failed but a real broker outcome can still be unknown. Durable acceptance requires status + outbox in one database transaction.
// Package main is the alternative to blocking on a reply: accept the work,
// return 202 Accepted with a status resource, and let the client poll.
package main
import (
"encoding/json"
"net/http"
"sync"
"time"
"github.com/google/uuid"
)
type Job struct {
ID string `json:"id"`
State string `json:"state"` // queued | done | failed
Result string `json:"result,omitempty"`
}
// Store is the status table. In production this is a database row, not a map.
type Store struct {
mu sync.Mutex
jobs map[string]Job
}
func (s *Store) Put(j Job) {
s.mu.Lock()
defer s.mu.Unlock()
s.jobs[j.ID] = j
}
func (s *Store) Get(id string) (Job, bool) {
s.mu.Lock()
defer s.mu.Unlock()
j, ok := s.jobs[id]
return j, ok
}
// Publisher puts the command on a broker. The worker that consumes it calls
// Store.Put with state "done" when it finishes.
type Publisher interface {
Publish(jobID string, body []byte) error
}
func NewMux(store *Store, pub Publisher) *http.ServeMux {
mux := http.NewServeMux()
mux.HandleFunc("POST /quotes", func(w http.ResponseWriter, r *http.Request) {
if pub == nil {
http.Error(w, "publisher not configured", http.StatusServiceUnavailable)
return
}
id := uuid.NewString()
store.Put(Job{ID: id, State: "queued"})
if err := pub.Publish(id, []byte(r.URL.Query().Get("sku"))); err != nil {
store.Put(Job{ID: id, State: "failed"})
// A real publish error may have an unknown outcome: reconcile using a DB outbox.
http.Error(w, "broker unavailable", http.StatusServiceUnavailable)
return
}
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Location", "/quotes/"+id)
w.Header().Set("Retry-After", "1")
w.WriteHeader(http.StatusAccepted)
_ = json.NewEncoder(w).Encode(Job{ID: id, State: "queued"})
})
mux.HandleFunc("GET /quotes/{id}", func(w http.ResponseWriter, r *http.Request) {
job, ok := store.Get(r.PathValue("id"))
if !ok {
http.NotFound(w, r)
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(job) // 200 with the current state
})
return mux
}
func main() {
store := &Store{jobs: map[string]Job{}}
_ = http.ListenAndServe(":8080", NewMux(store, localPublisher{store}))
}
// A runnable teaching substitute, NOT durable acceptance: process exit loses jobs.
// Production persists status + outbox atomically; a relay publishes and a worker
// updates the status. Neither afterCommit nor this goroutine closes that crash gap.
type localPublisher struct{ store *Store }
func (p localPublisher) Publish(id string, body []byte) error {
go func() {
time.Sleep(100 * time.Millisecond)
p.store.Put(Job{ID: id, State: "done", Result: "quote for " + string(body)})
}()
return nil
}To push the result to a browser, Server-Sent Events need only net/http: subscribe, flush a comment line, wait for the result or for the client to leave.
This hub is a live-notification sketch, not durable status storage. Authorize the browser and internal endpoint, then subscribe before fetching durable status to close the completion race.
// Package main delivers an asynchronous reply to a browser with
// Server-Sent Events: POST returns 202, GET /quotes/{id}/events streams the
// result when a worker finishes. A WebSocket or Reverb channel plays the
// same role when the browser also needs to send.
package main
import (
"fmt"
"net/http"
"sync"
"time"
)
// Hub fans a finished result out to whoever is watching that id. In a real
// system the worker publishes to Redis/RabbitMQ and every web node has a hub.
type Hub struct {
mu sync.Mutex
subs map[string][]chan string
}
func NewHub() *Hub { return &Hub{subs: map[string][]chan string{}} }
func (h *Hub) Subscribe(id string) (<-chan string, func()) {
ch := make(chan string, 1) // buffered: Publish never blocks on a slow browser
h.mu.Lock()
h.subs[id] = append(h.subs[id], ch)
h.mu.Unlock()
return ch, func() {
h.mu.Lock()
defer h.mu.Unlock()
list := h.subs[id]
for i, c := range list {
if c == ch {
h.subs[id] = append(list[:i], list[i+1:]...)
break
}
}
}
}
func (h *Hub) Publish(id, payload string) {
h.mu.Lock()
defer h.mu.Unlock()
for _, c := range h.subs[id] {
select {
case c <- payload:
default: // already has a pending value
}
}
delete(h.subs, id)
}
func events(h *Hub) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
fl, ok := w.(http.Flusher)
if !ok {
http.Error(w, "streaming unsupported", http.StatusInternalServerError)
return
}
ch, cancel := h.Subscribe(r.PathValue("id"))
defer cancel()
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
fmt.Fprint(w, ": connected\n\n")
fl.Flush()
keepAlive := time.NewTicker(15 * time.Second) // comment lines keep proxies from idling out
defer keepAlive.Stop()
for {
select {
case msg := <-ch:
fmt.Fprintf(w, "event: quote.ready\ndata: %s\n\n", msg)
fl.Flush()
return
case <-keepAlive.C:
fmt.Fprint(w, ": ping\n\n")
fl.Flush()
case <-r.Context().Done(): // browser left: stop waiting
return
}
}
}
}
func main() {
hub := NewHub()
mux := http.NewServeMux()
mux.HandleFunc("GET /quotes/{id}/events", events(hub))
mux.HandleFunc("POST /internal/quotes/{id}/ready", func(w http.ResponseWriter, r *http.Request) {
hub.Publish(r.PathValue("id"), `{"price_cents":1999}`)
w.WriteHeader(http.StatusNoContent)
})
srv := &http.Server{Addr: ":8080", Handler: mux, ReadHeaderTimeout: 5 * time.Second}
_ = srv.ListenAndServe()
}To push it to another server, a webhook with backoff and a stable Idempotency-Key.
// Package main delivers a result to a caller's callback URL. The sender
// retries with backoff and sends a stable Idempotency-Key, because the
// receiver will see duplicates (a timeout does not mean the callback failed).
package main
import (
"bytes"
"context"
"fmt"
"net/http"
"time"
)
// Deliver POSTs payload to url, retrying on network errors and 5xx.
func Deliver(ctx context.Context, c *http.Client, url, requestID string, payload []byte) error {
backoff := 500 * time.Millisecond
var last error
for attempt := 1; attempt <= 5; attempt++ {
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(payload))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Idempotency-Key", requestID) // same key on every attempt
resp, err := c.Do(req)
if err == nil {
resp.Body.Close()
if resp.StatusCode < 300 {
return nil
}
if resp.StatusCode < 500 && resp.StatusCode != http.StatusTooManyRequests {
return fmt.Errorf("callback rejected with %d: do not retry", resp.StatusCode)
}
last = fmt.Errorf("callback returned %d", resp.StatusCode)
} else {
last = err
}
select {
case <-time.After(backoff):
backoff *= 2
case <-ctx.Done():
return ctx.Err()
}
}
return fmt.Errorf("giving up after 5 attempts: %w", last)
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
c := &http.Client{Timeout: 5 * time.Second}
// Compile-only example; nothing listens on this address.
_ = Deliver(ctx, c, "http://localhost:9999/hooks/quote", "req-123", []byte(`{"price_cents":1999}`))
}And when the answer is needed now, the plain alternative: net/http with a client timeout, a total deadline, bounded retries on an idempotent GET, and traceparent forwarded.
// Package main is the plain alternative: when the caller needs the answer
// now, call the service over HTTP with a deadline, a bounded retry on an
// idempotent request, and the trace context forwarded.
package main
import (
"context"
"fmt"
"io"
"log"
"net/http"
"time"
)
var client = &http.Client{
Timeout: 2 * time.Second, // hard ceiling for one attempt, including reading the body
Transport: &http.Transport{
MaxIdleConnsPerHost: 50,
ResponseHeaderTimeout: 1500 * time.Millisecond,
},
}
// GetQuote retries only because GET is idempotent (RFC 9110 section 9.2.2).
// A POST needs an Idempotency-Key before it may be retried.
func GetQuote(ctx context.Context, traceparent, sku string) ([]byte, error) {
ctx, cancel := context.WithTimeout(ctx, 3*time.Second) // total budget for all attempts
defer cancel()
var last error
for attempt := 0; attempt < 3; attempt++ {
req, err := http.NewRequestWithContext(ctx, http.MethodGet,
"http://pricing.internal/quotes/"+sku, nil)
if err != nil {
return nil, err
}
req.Header.Set("traceparent", traceparent)
resp, err := client.Do(req)
if err == nil {
body, rerr := io.ReadAll(resp.Body)
resp.Body.Close()
if rerr == nil && resp.StatusCode == http.StatusOK {
return body, nil
}
if resp.StatusCode < 500 {
return nil, fmt.Errorf("pricing returned %d", resp.StatusCode)
}
last = fmt.Errorf("pricing returned %d", resp.StatusCode)
} else {
last = err
}
select {
case <-time.After(time.Duration(100<<attempt) * time.Millisecond):
case <-ctx.Done():
return nil, ctx.Err()
}
}
return nil, last
}
func main() {
_, err := GetQuote(context.Background(), "00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01", "A-1")
log.Println("result:", err)
}The Go angle
context.Context is what makes request-reply tolerable in Go: the select on ctx.Done() bounds reply waiting. In amqp091-go v1.17.0, PublishWithContext checks cancellation before publishing but cannot interrupt an in-flight socket write; configure bounded transport writes as shown, and http.Request.Context() cancels the call when the client disconnects. Hohpe and Woolf's "Asynchronous Callback" maps onto a goroutine plus a map[string]chan result, with one rule that is easy to break: make the waiter channel buffered (size 1), so the dispatcher never blocks on a caller that has already left. The Before snippet breaks it. In amqp091-go, the channel returned by Channel.Consume is closed when the channel or connection closes or the consumer is cancelled; ranging over it ends, which is the moment to fail the pending table. Publisher-side, Channel.NotifyReturn delivers basic.return for unroutable mandatory publishes. Go 1.22's ServeMux patterns ("GET /quotes/{id}", r.PathValue) are enough for a status endpoint without a router library. The Go standard library also gives you http.Flusher for SSE and http.Client.Timeout as a hard cap per attempt.
Laravel
Before
A controller dispatches a job, then polls the quotes table in a while (true) loop. It holds a PHP-FPM worker for as long as the queue is slow, and never returns if the job fails permanently.
<?php
namespace App\Http\Controllers;
use App\Jobs\BuildQuote;
use App\Models\Quote;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
class QuoteController
{
// Sync over async: dispatch a job, then hold the HTTP request open and
// poll the database until the worker has written the answer.
public function store(Request $request): JsonResponse
{
$quote = Quote::create([
'id' => (string) Str::uuid(),
'sku' => $request->string('sku'),
'state' => 'queued',
]);
BuildQuote::dispatch($quote->id);
// No deadline: this FPM worker is pinned for as long as the queue is
// slow, the worker is down, or the job has failed for good.
while (true) {
$quote->refresh();
if ($quote->state === 'done') {
return response()->json(['price' => $quote->price]);
}
usleep(200_000);
}
}
}After
202 Accepted plus a Location header, a job that writes the result into the same row, and a failed() hook that writes the failure into it too. The status row is the reply channel. Authenticate and authorize its owner; validate input. afterCommit orders dispatch but does not atomically commit the database and broker; use an outbox for durable acceptance.
<?php
namespace App\Http\Controllers;
use App\Jobs\BuildQuote;
use App\Models\Quote;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
// routes/api.php
// Route::post('/quotes', [QuoteController::class, 'store']);
// Route::get('/quotes/{quote}', [QuoteController::class, 'show'])->name('quotes.show');
class QuoteController
{
// Teaching skeleton: authenticate/authorize the owner and validate SKU.
// Production needs status + transactional outbox for durable acceptance.
// afterCommit orders dispatch but does not make DB and broker commit atomic.
// Accept the work, answer 202 Accepted, point at a status resource.
public function store(Request $request): JsonResponse
{
$quote = Quote::create([
'id' => (string) Str::uuid(),
'sku' => $request->string('sku'),
'state' => 'queued',
]);
// Wait for the INSERT to commit before a worker can see the job.
BuildQuote::dispatch($quote->id)->afterCommit();
return response()
->json(['id' => $quote->id, 'state' => $quote->state], 202)
->header('Location', route('quotes.show', $quote))
->header('Retry-After', '1');
}
// The client polls this; it never blocks.
public function show(Quote $quote): JsonResponse
{
return response()->json([
'id' => $quote->id,
'state' => $quote->state,
'price' => $quote->price,
]);
}
}The job updates the row and then dispatches a broadcast event.
<?php
namespace App\Jobs;
use App\Events\QuoteReady;
use App\Models\Quote;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\Attributes\Timeout;
use Illuminate\Queue\Attributes\Tries;
use Throwable;
#[Tries(3)]
#[Timeout(30)]
class BuildQuote implements ShouldQueue
{
use Queueable;
public function __construct(public string $quoteId) {}
public function handle(): void
{
$quote = Quote::findOrFail($this->quoteId);
// Idempotent write: a retry after a crash simply overwrites the row.
$quote->forceFill([
'state' => 'done',
'price' => $this->priceFor($quote->sku),
])->save();
// Push the reply to the browser; ShouldBroadcast queues the broadcast.
QuoteReady::dispatch($quote);
}
// Called after the last attempt: the status row is the reply channel,
// so failures must be written to it too.
public function failed(?Throwable $exception): void
{
// A retry can fail while broadcasting after the result was already saved.
Quote::whereKey($this->quoteId)->where('state', '!=', 'done')->update(['state' => 'failed']);
}
private function priceFor(string $sku): int
{
return 4200; // stand-in for the real work
}
}The event goes to a private channel; Reverb (or Pusher, Ably) delivers it to the waiting browser. ShouldDispatchAfterCommit keeps the event from firing before the row is visible.
<?php
namespace App\Events;
use App\Models\Quote;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Contracts\Events\ShouldDispatchAfterCommit;
use Illuminate\Foundation\Events\Dispatchable;
// The asynchronous "reply" for a browser: the job finishes, Reverb (or Pusher,
// Ably) pushes this event to the page that is waiting on the quote.
class QuoteReady implements ShouldBroadcast, ShouldDispatchAfterCommit
{
use Dispatchable, InteractsWithSockets;
public function __construct(public Quote $quote) {}
public function broadcastOn(): array
{
// Private channel: only the owner may listen (see routes/channels.php).
return [new PrivateChannel('quotes.'.$this->quote->id)];
}
public function broadcastAs(): string
{
return 'quote.ready';
}
public function broadcastWith(): array
{
return ['id' => $this->quote->id, 'state' => $this->quote->state, 'price' => $this->quote->price];
}
}<?php
use App\Models\Quote;
use Illuminate\Support\Facades\Broadcast;
// routes/channels.php. Echo asks this callback before it lets a browser
// subscribe to the private channel.
Broadcast::channel('quotes.{quoteId}', function ($user, string $quoteId) {
return Quote::whereKey($quoteId)->where('user_id', $user->id)->exists();
});A notification does the same job for people who closed the tab: stored in the database channel and pushed on the broadcast channel.
<?php
namespace App\Notifications;
use App\Models\Quote;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\BroadcastMessage;
use Illuminate\Notifications\Notification;
// Notification flavour of the same reply: stored for later (database) and
// pushed live (broadcast). A user who closed the tab still finds it later.
class QuoteReadyNotification extends Notification implements ShouldQueue
{
use Queueable;
public function __construct(public Quote $quote)
{
$this->afterCommit();
}
public function via(object $notifiable): array
{
return ['database', 'broadcast'];
}
public function toArray(object $notifiable): array
{
return ['quote_id' => $this->quote->id, 'price' => $this->quote->price];
}
public function toBroadcast(object $notifiable): BroadcastMessage
{
return new BroadcastMessage($this->toArray($notifiable));
}
}Three ways to run the same job, so the difference between in-process, queued and sync-over-async is visible in one file.
<?php
namespace App\Http\Controllers;
use App\Jobs\BuildQuote;
use App\Models\Quote;
use Illuminate\Http\JsonResponse;
// Three ways to run the same job; only the last one is request-reply.
class DispatchModes
{
// 1. In-process, in the web request. No queue, no broker: this is a
// function call that happens to be shaped like a job.
public function inline(Quote $quote): JsonResponse
{
BuildQuote::dispatchSync($quote->id);
return response()->json($quote->fresh());
}
// 2. Queued, fire and forget. The response cannot contain the result.
public function queued(Quote $quote): JsonResponse
{
BuildQuote::dispatch($quote->id)->afterCommit();
return response()->json(['state' => 'queued'], 202);
}
// 3. Queued and awaited: sync over async. Do not ship this; it is here to
// be recognised in code review.
public function blocking(Quote $quote): JsonResponse
{
BuildQuote::dispatch($quote->id)->afterCommit();
$deadline = microtime(true) + 5;
while (microtime(true) < $deadline) {
$quote->refresh();
if ($quote->state !== 'queued') {
return response()->json($quote);
}
usleep(200_000); // holds a PHP-FPM worker the whole time
}
return response()->json(['state' => 'timeout'], 504);
}
}The synchronous alternative with the Http client: connect and total timeouts, bounded retries on connection errors and 5xx only, one Idempotency-Key for all attempts, traceparent forwarded.
<?php
namespace App\Clients;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;
use Throwable;
// The synchronous alternative: when the caller needs the answer now, call
// the service over HTTP with a deadline and an idempotency key.
class HttpQuoteClient
{
public function create(string $sku, string $traceparent): array
{
// One key per logical request, reused by every retry of it.
$key = (string) Str::uuid();
return Http::baseUrl(config('services.pricing.url'))
->withHeaders([
'Idempotency-Key' => $key,
'traceparent' => $traceparent,
])
->connectTimeout(1)
->timeout(3)
// Retry connection errors and 5xx only; a 4xx is the caller's bug.
->retry(
[100, 300],
when: fn (Throwable $e) => $e instanceof ConnectionException
|| ($e instanceof RequestException && $e->response->serverError()),
throw: false,
)
->post('/quotes', ['sku' => $sku])
->throw()
->json();
}
}The PHP RPC client supports one outstanding call at a time; do not share it across concurrent coroutines. Configure bounded socket read/write timeouts on the connection as well as the monotonic reply-loop deadline.
When a real RPC over RabbitMQ is needed, this is the php-amqplib client from RabbitMQ's PHP tutorial 6, adapted to Direct Reply-To and a deadline.
<?php
namespace App\Messaging;
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Exception\AMQPTimeoutException;
use PhpAmqpLib\Message\AMQPMessage;
use RuntimeException;
use InvalidArgumentException;
use PhpAmqpLib\Wire\AMQPTable;
// Raw php-amqplib (the laravel-queue-rabbitmq package is a queue driver and
// exposes no request-reply client). Follows RabbitMQ tutorial 6 for PHP, with
// Direct Reply-To instead of a declared callback queue.
class RabbitRpcClient
{
private const REPLY_TO = 'amq.rabbitmq.reply-to';
private $channel;
private ?string $response = null;
private string $correlationId = '';
public function __construct(AMQPStreamConnection $connection, private string $requestQueue)
{
$this->channel = $connection->channel();
// Consume the pseudo-queue in no-ack mode on the SAME channel that
// will publish the requests.
$this->channel->basic_consume(
self::REPLY_TO,
'',
false,
true, // no_ack
false,
false,
function (AMQPMessage $reply): void {
if ($reply->get('correlation_id') === $this->correlationId) {
$this->response = $reply->getBody();
}
// Any other correlation id is a late reply to an abandoned call.
},
);
}
public function call(string $body, float $timeoutSeconds = 2.0): string
{
if ($timeoutSeconds <= 0 || ! is_finite($timeoutSeconds)) {
throw new InvalidArgumentException('positive finite timeout required');
}
$deadline = hrtime(true) + (int) ($timeoutSeconds * 1_000_000_000);
$this->response = null;
$this->correlationId = bin2hex(random_bytes(16));
$this->channel->basic_publish(new AMQPMessage($body, [
'correlation_id' => $this->correlationId,
'reply_to' => self::REPLY_TO,
'expiration' => (string) max(1, (int) ($timeoutSeconds * 1000)),
'application_headers' => new AMQPTable([
'deadline_unix_ms' => (string) (int) ((microtime(true) + $timeoutSeconds) * 1000),
]),
]), '', $this->requestQueue);
// The connection must also have bounded socket read/write timeouts.
// This loop deadline cannot interrupt a socket write already in progress.
while ($this->response === null) {
$remaining = ($deadline - hrtime(true)) / 1_000_000_000;
if ($remaining <= 0) {
throw new RuntimeException('RPC timed out');
}
try {
$this->channel->wait(null, false, $remaining);
} catch (AMQPTimeoutException) {
throw new RuntimeException('RPC timed out');
}
}
return $this->response;
}
}And the replier as a long-running Artisan command, because the queue driver does not do replies.
<?php
namespace App\Console\Commands;
use App\Services\PricingService;
use Illuminate\Console\Command;
use PhpAmqpLib\Channel\AMQPChannel;
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;
use PhpAmqpLib\Wire\AMQPTable;
use RuntimeException;
use JsonException;
// php artisan rpc:serve
// The replier of a RabbitMQ RPC, written against php-amqplib. The
// laravel-queue-rabbitmq driver consumes Laravel jobs and sets no reply_to,
// so a request-reply server is a separate long-running command.
class RpcServeCommand extends Command
{
protected $signature = 'rpc:serve {--queue=quotes.rpc}';
protected $description = 'Answer RabbitMQ RPC requests using reply_to and correlation_id';
public function handle(PricingService $pricing): int
{
$connection = new AMQPStreamConnection(
config('queue.connections.rabbitmq.hosts.0.host', 'localhost'),
(int) config('queue.connections.rabbitmq.hosts.0.port', 5672),
config('queue.connections.rabbitmq.hosts.0.user', 'guest'),
config('queue.connections.rabbitmq.hosts.0.password', 'guest'),
);
$channel = $connection->channel();
$queue = (string) $this->option('queue');
$channel->queue_declare($queue, false, true, false, false, false, new AMQPTable(['x-queue-type' => 'quorum']));
$channel->confirm_select();
$channel->set_nack_handler(static function (): void { throw new RuntimeException('reply rejected by broker'); });
$channel->set_return_listener(function (): void { $this->warn('ordinary reply queue has no route'); });
$channel->basic_qos(null, 1, null); // one unacked request per worker
$channel->basic_consume($queue, '', false, false, false, false,
function (AMQPMessage $request) use ($pricing, $channel): void {
$this->reply($channel, $request, $pricing);
});
while ($channel->is_consuming()) {
$channel->wait();
}
return self::SUCCESS;
}
private function reply(AMQPChannel $channel, AMQPMessage $request, PricingService $pricing): void
{
if (! $request->has('reply_to') || ! $request->has('correlation_id')) {
$request->nack(false); // no return address: reject; DLX if configured, otherwise discard
return;
}
// Require a usable, unexpired deadline before expensive work. Monitor clock skew.
$headers = $request->has('application_headers') ? $request->get('application_headers')->getNativeData() : [];
$deadline = filter_var($headers['deadline_unix_ms'] ?? null, FILTER_VALIDATE_INT);
if ($deadline === false || $deadline <= (int) (microtime(true) * 1000)) {
$request->nack(false);
return;
}
try {
$payload = json_decode($request->getBody(), true, flags: JSON_THROW_ON_ERROR);
} catch (JsonException) {
$request->nack(false);
return;
}
if (! is_array($payload) || ! is_string($payload['sku'] ?? null)) {
$request->nack(false);
return;
}
$sku = $payload['sku'] ?? '';
// PricingService must also bound downstream I/O; the check cannot cancel committed effects.
$body = json_encode(['sku' => $sku, 'price_cents' => $pricing->priceFor($sku)]);
$channel->basic_publish(
new AMQPMessage($body, [
'content_type' => 'application/json',
'correlation_id' => $request->get('correlation_id'),
]),
'',
$request->get('reply_to'),
true, // missing ordinary queue; Direct Reply-To is always considered routed
);
$channel->wait_for_pending_acks_returns(3.0);
$request->ack(); // broker acceptance, NOT proof the requester received the reply
}
}The Laravel angle
Laravel's queue is built for the fire-and-forget half of the problem: Job::dispatch() returns a PendingDispatch, not the queued job’s eventual result, and there is no reply channel in ShouldQueue. That is deliberate, so the idiomatic reply is a row (or a cached value) keyed by a UUID that the job updates, plus a broadcast or notification for the push. Facts checked against the Laravel 13 docs:
| Feature | What it does | Use here |
|---|---|---|
Job::dispatch(...)->afterCommit() | Dispatch only after open DB transactions commit | The worker must not see the job before the status row exists |
after_commit queue connection option | Same, for all jobs on the connection | Safe default |
Job::dispatchSync() | Run now, in the current process, no queue | A function call dressed as a job; fine in a monolith, not a reply channel |
#[Tries], #[Timeout] attributes | Bound attempts and run time of a job | A poison job ends in failed() instead of polling forever |
failed() on a job | Called after the last attempt | Write state=failed into the status row |
ShouldBroadcast + PrivateChannel | Queues a broadcast to a channel Echo must authorise | Reply to a browser |
ShouldDispatchAfterCommit (event) | Event fires after the transaction commits | Same ordering guarantee as afterCommit() |
Notifications database and broadcast channels | Store and push | Reply to a person who may be offline |
| Reverb | First-party WebSocket server (php artisan reverb:start) | Self-hosted push without Pusher |
Http::timeout(), connectTimeout(), retry() | Deadline and retries for REST | The synchronous side |
Http::withHeaders() | Add Idempotency-Key, traceparent | Safe retries, trace continuity |
The HTTP client bounds each attempt, not the total time across all retries; the caller needs a total budget. Two details matter. First, a ShouldBroadcast event uses a queued broadcast job, so a queue worker must run; ShouldBroadcastNow is the explicit synchronous alternative. Second, retrying a non-idempotent POST is how duplicate orders happen: pair retry() with an idempotency key. About RabbitMQ: I read the source of vladimir-yuldashev/laravel-queue-rabbitmq (v15.0.2 on Packagist): createMessage() sets content_type, persistent delivery mode and, if the Laravel payload has an id, correlation_id. It sets no reply_to, so the package is a job transport, not an RPC client; the snippets above use php-amqplib directly (the package depends on it).
Broker differences
RabbitMQ
RabbitMQ has first-class support: the AMQP 0-9-1 properties reply_to and correlation_id are part of every message, and the default exchange routes by queue name. A request goes to a durable (quorum) request queue consumed by competing repliers with prefetch=1; the reply goes to the queue named in reply_to. Four reply shapes exist: a queue per call (inefficient), an exclusive auto-delete queue per client (tutorial 6), a long-lived named queue (survives reconnects, needs x-expires), and Direct Reply-To. The pseudo-queue amq.rabbitmq.reply-to has the limits listed above: no-ack, one channel, one consumer per channel, at-most-once, invisible in list_queues. RPC timeouts are yours: pair a caller deadline with the request expiration. A requester that dies takes its exclusive queue with it; publish replies with mandatory and watch basic.return, except for Direct Reply-To where the generated destination counts as routed regardless of requester presence. The Go client is in Go; the PHP client and replier command are in Laravel. See also RabbitMQ in depth.
// Package main is a RabbitMQ RPC client using Direct Reply-To and a context
// timeout. One consumer on one channel serves every concurrent call.
package main
import (
"context"
"errors"
"fmt"
"log"
"net"
"os"
"strconv"
"sync"
"time"
"github.com/google/uuid"
amqp "github.com/rabbitmq/amqp091-go"
)
const directReplyTo = "amq.rabbitmq.reply-to"
type Client struct {
ch *amqp.Channel
queue string
mu sync.Mutex
pending map[string]chan result
closed bool
}
type result struct {
body []byte
err error
}
// ErrReplyChannelLost is returned to every waiter when the reply consumer
// ends (channel or connection closed, consumer cancelled). Direct Reply-To
// replies are at-most-once. Retry only idempotent or deduplicated operations.
var ErrReplyChannelLost = errors.New("reply consumer closed; outcome may be unknown")
// NewClient consumes from the pseudo-queue in no-ack mode. The same channel
// must be used to publish requests (RabbitMQ Direct Reply-To rule).
func NewClient(ch *amqp.Channel, requestQueue string) (*Client, error) {
replies, err := ch.Consume(directReplyTo, "", true, false, false, false, nil)
if err != nil {
return nil, fmt.Errorf("consume reply-to: %w", err)
}
c := &Client{ch: ch, queue: requestQueue, pending: map[string]chan result{}}
go func() {
for d := range replies {
c.mu.Lock()
w, ok := c.pending[d.CorrelationId]
delete(c.pending, d.CorrelationId)
c.mu.Unlock()
if !ok {
continue // late or duplicate reply: nobody is waiting, drop it
}
w <- result{body: d.Body} // buffered, never blocks
}
// The deliveries channel closed: fail everyone instead of letting
// them wait for their full deadline.
c.mu.Lock()
c.closed = true
for id, w := range c.pending {
w <- result{err: ErrReplyChannelLost}
delete(c.pending, id)
}
c.mu.Unlock()
}()
return c, nil
}
// Call publishes a request and waits for the reply or ctx.Done().
func (c *Client) Call(ctx context.Context, body []byte) ([]byte, error) {
if _, ok := ctx.Deadline(); !ok {
return nil, errors.New("RPC requires a deadline")
}
if err := ctx.Err(); err != nil {
return nil, err
}
deadline, _ := ctx.Deadline()
id := uuid.NewString()
wait := make(chan result, 1)
c.mu.Lock()
if c.closed {
c.mu.Unlock()
return nil, ErrReplyChannelLost
}
if len(c.pending) >= 256 {
c.mu.Unlock()
return nil, errors.New("RPC in-flight limit reached")
}
c.pending[id] = wait
c.mu.Unlock()
defer func() {
c.mu.Lock()
delete(c.pending, id) // timed out: later replies become orphans
c.mu.Unlock()
}()
err := c.ch.PublishWithContext(ctx, "", c.queue, false, false, amqp.Publishing{
ContentType: "application/json",
CorrelationId: id,
ReplyTo: directReplyTo,
Expiration: strconv.FormatInt(max(1, time.Until(deadline).Milliseconds()), 10), // queue residence only
Headers: amqp.Table{"deadline_unix_ms": strconv.FormatInt(deadline.UnixMilli(), 10)},
Body: body,
})
if err != nil {
return nil, err
}
select {
case res := <-wait:
return res.body, res.err
case <-ctx.Done():
return nil, ctx.Err()
}
}
func main() {
url := os.Getenv("AMQP_URL")
if url == "" {
log.Fatal("set AMQP_URL, e.g. amqp://guest:guest@localhost:5672/")
}
conn, err := amqp.DialConfig(url, amqp.Config{
Dial: func(network, address string) (net.Conn, error) {
c, err := net.DialTimeout(network, address, time.Second)
if err != nil {
return nil, err
}
return &boundedWriteConn{Conn: c}, nil
},
})
if err != nil {
log.Fatal(err)
}
defer conn.Close()
ch, err := conn.Channel()
if err != nil {
log.Fatal(err)
}
client, err := NewClient(ch, "quotes.rpc")
if err != nil {
log.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
reply, err := client.Call(ctx, []byte(`{"sku":"A-1"}`))
log.Printf("reply=%s err=%v", reply, err)
}
// Reply is the responder side: publish to the default exchange using the
// request's ReplyTo as the routing key, and copy the correlation id.
func Reply(ctx context.Context, ch *amqp.Channel, req amqp.Delivery, body []byte) error {
return ch.PublishWithContext(ctx, "", req.ReplyTo, false, false, amqp.Publishing{
CorrelationId: req.CorrelationId,
ContentType: "application/json",
Body: body,
})
}
// Context cancellation cannot interrupt an amqp091-go socket write. This
// connection-wide cap bounds each write; it is separate from the RPC deadline.
// Shared connections must not be closed just to cancel one individual call.
type boundedWriteConn struct{ net.Conn }
func (c *boundedWriteConn) Write(p []byte) (int, error) {
if err := c.Conn.SetWriteDeadline(time.Now().Add(time.Second)); err != nil {
return 0, err
}
return c.Conn.Write(p)
}Kafka
Kafka has no reply-to primitive: a record has key, value and headers, and nothing in the protocol designates an answer address. Headers (KIP-82) are the conventional place for correlation-id, reply-topic and reply-partition. The pitfalls are structural and are tabulated above: a shared reply topic means every instance reads everyone's replies; a per-requester topic makes topic creation your per-instance cost; a reply partition per instance needs manual assignment and a replier using kgo.ManualPartitioner(); group rebalances add seconds; replies are retained, not dropped. Spring's ReplyingKafkaTemplate is the reference implementation of the idea. Kafka suits command and event flows, with replies as events; for sub-second synchronous answers it is rarely the right tool. In Laravel, mateusjunges/laravel-kafka is a producer/consumer package; I did not find a documented request-reply client in it, so write the reply as a plain produce to the reply topic with the correlation header. See Kafka in depth and ordering.
This sketch starts at the retained beginning and filters old correlation ids, avoiding an asynchronously resolved AtEnd offset skipping an early reply. Production needs exclusive logical partition ownership, persisted recovery offsets, bounded pending state and reader lifecycle handling.
// Package main sketches Kafka request-reply with franz-go. Kafka has no
// reply-to primitive, so the requester claims one partition of a shared
// reply topic and says so in a header; the replier produces back to it.
package main
import (
"context"
"errors"
"log"
"os"
"strconv"
"sync"
"time"
"github.com/google/uuid"
"github.com/twmb/franz-go/pkg/kgo"
)
const (
requestTopic = "quotes.requests"
replyTopic = "quotes.replies"
)
type Requester struct {
cl *kgo.Client
partition int32
mu sync.Mutex
pending map[string]chan []byte
}
func NewRequester(brokers []string, partition int32) (*Requester, error) {
cl, err := kgo.NewClient(
kgo.SeedBrokers(brokers...),
// Read our assigned partition from its retained start, filtering old ids.
// AtEnd resolved asynchronously can skip a reply produced before offset lookup.
// No consumer group:
// a rebalance here would add seconds of latency to every call.
kgo.ConsumePartitions(map[string]map[int32]kgo.Offset{
replyTopic: {partition: kgo.NewOffset().AtStart()},
}),
)
if err != nil {
return nil, err
}
r := &Requester{cl: cl, partition: partition, pending: map[string]chan []byte{}}
go r.pump(context.Background())
return r, nil
}
func (r *Requester) pump(ctx context.Context) {
for {
fetches := r.cl.PollFetches(ctx)
if fetches.IsClientClosed() || ctx.Err() != nil {
return
}
fetches.EachRecord(func(rec *kgo.Record) {
var corr string
for _, h := range rec.Headers {
if h.Key == "correlation-id" {
corr = string(h.Value)
}
}
r.mu.Lock()
w, ok := r.pending[corr]
delete(r.pending, corr)
r.mu.Unlock()
if ok {
w <- rec.Value // orphans (timed out calls) are skipped
}
})
}
}
func (r *Requester) Call(ctx context.Context, key, body []byte) ([]byte, error) {
if _, ok := ctx.Deadline(); !ok {
return nil, errors.New("RPC requires a deadline")
}
id := uuid.NewString()
wait := make(chan []byte, 1)
r.mu.Lock()
r.pending[id] = wait
r.mu.Unlock()
defer func() {
r.mu.Lock()
delete(r.pending, id)
r.mu.Unlock()
}()
rec := &kgo.Record{
Topic: requestTopic,
Key: key,
Value: body,
Headers: []kgo.RecordHeader{
{Key: "correlation-id", Value: []byte(id)},
{Key: "reply-topic", Value: []byte(replyTopic)},
{Key: "reply-partition", Value: []byte(strconv.Itoa(int(r.partition)))},
},
}
if err := r.cl.ProduceSync(ctx, rec).FirstErr(); err != nil {
return nil, err
}
select {
case v := <-wait:
return v, nil
case <-ctx.Done():
return nil, ctx.Err()
}
}
// Reply runs on the replier: copy the correlation header and produce to the
// partition named in the request. The producer must use ManualPartitioner.
func Reply(ctx context.Context, cl *kgo.Client, req *kgo.Record, body []byte) error {
var corr, topic, part []byte
for _, h := range req.Headers {
switch h.Key {
case "correlation-id":
corr = h.Value
case "reply-topic":
topic = h.Value
case "reply-partition":
part = h.Value
}
}
p, err := strconv.ParseInt(string(part), 10, 32)
if err != nil || p < 0 || string(topic) != replyTopic || len(corr) == 0 {
return errors.New("request has no usable reply headers")
}
return cl.ProduceSync(ctx, &kgo.Record{
Topic: string(topic),
Partition: int32(p),
Value: body,
Headers: []kgo.RecordHeader{{Key: "correlation-id", Value: corr}},
}).FirstErr()
}
// NewReplierClient builds the replier's producer with manual partitioning.
func NewReplierClient(brokers []string) (*kgo.Client, error) {
return kgo.NewClient(
kgo.SeedBrokers(brokers...),
kgo.RecordPartitioner(kgo.ManualPartitioner()),
)
}
func main() {
broker := os.Getenv("KAFKA_BROKER")
if broker == "" {
log.Fatal("set KAFKA_BROKER, e.g. localhost:9092")
}
r, err := NewRequester([]string{broker}, 0)
if err != nil {
log.Fatal(err)
}
defer r.cl.Close()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
reply, err := r.Call(ctx, []byte("A-1"), []byte(`{"sku":"A-1"}`))
log.Printf("reply=%s err=%v", reply, err)
}Redis Streams
Redis offers two shapes. Pub/Sub is cheap, but its delivery is at-most-once and a reply published before the requester subscribes is gone, so subscribe first (snippet below). Streams give a durable reply: the request goes on a shared stream read by a consumer group, and each requester owns a reply stream whose name travels in the request (reply_to). The second snippet tails that stream by last-seen id (not $), and the replier sets an EXPIRE on it so orphaned replies and dead requesters do not leak memory; the expiry is on the whole key, not on individual entries. Laravel's own redis queue driver uses lists and sorted sets, not streams, so a stream reply from Laravel uses the Redis facade (Redis::xadd, Redis::xread). See Redis Streams & Pub/Sub and Redis.
// Package main uses Redis Pub/Sub for a reply. It works only because the
// requester SUBSCRIBES FIRST: Pub/Sub keeps nothing, so a reply published
// before the subscription is active is gone (at-most-once).
package main
import (
"context"
"log"
"os"
"time"
"github.com/google/uuid"
"github.com/redis/go-redis/v9"
)
// Call puts the request on a durable stream and waits for one Pub/Sub reply
// on a per-request channel. If it times out the caller decides what to do.
func Call(ctx context.Context, rdb *redis.Client, body string) (string, error) {
id := uuid.NewString()
replyChan := "reply:" + id
sub := rdb.Subscribe(ctx, replyChan)
defer sub.Close()
if _, err := sub.Receive(ctx); err != nil { // wait for the SUBSCRIBE confirmation
return "", err
}
err := rdb.XAdd(ctx, &redis.XAddArgs{
Stream: "quotes:requests",
MaxLen: 10_000, Approx: true,
Values: map[string]any{"correlation_id": id, "reply_to": replyChan, "body": body},
}).Err()
if err != nil {
return "", err
}
select {
case msg := <-sub.Channel():
return msg.Payload, nil
case <-ctx.Done():
return "", ctx.Err()
}
}
func main() {
addr := os.Getenv("REDIS_ADDR")
if addr == "" {
log.Fatal("set REDIS_ADDR, e.g. localhost:6379")
}
rdb := redis.NewClient(&redis.Options{Addr: addr})
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
reply, err := Call(ctx, rdb, `{"sku":"A-1"}`)
log.Printf("reply=%s err=%v", reply, err)
}The Streams sketch reads new requests; production must add pending recovery (XAUTOCLAIM), logical deduplication and an atomic reply/expiry policy. XGROUP starts at 0 to include pre-existing requests. XADD/EXPIRE are separate operations here, so expiry errors must be handled.
// Package main sketches request-reply on Redis Streams: a shared request
// stream with a consumer group, and one reply stream per requester instance.
package main
import (
"context"
"errors"
"fmt"
"log"
"os"
"strings"
"sync"
"time"
"github.com/google/uuid"
"github.com/redis/go-redis/v9"
)
const requestStream = "quotes:requests"
type Requester struct {
rdb *redis.Client
replyStream string
mu sync.Mutex
pending map[string]chan string
}
func NewRequester(rdb *redis.Client) *Requester {
r := &Requester{
rdb: rdb,
replyStream: "quotes:replies:" + uuid.NewString(),
pending: map[string]chan string{},
}
go r.pump(context.Background())
return r
}
// pump tails our private reply stream, remembering the last id it saw so no
// reply is missed between two blocking reads.
func (r *Requester) pump(ctx context.Context) {
last := "0"
for ctx.Err() == nil {
streams, err := r.rdb.XRead(ctx, &redis.XReadArgs{
Streams: []string{r.replyStream, last},
Block: time.Second,
}).Result()
if err != nil {
if !errors.Is(err, redis.Nil) {
select {
case <-ctx.Done():
return
case <-time.After(200 * time.Millisecond):
}
}
continue // no busy-spin during an outage
}
for _, msg := range streams[0].Messages {
last = msg.ID
corr, _ := msg.Values["correlation_id"].(string)
body, _ := msg.Values["body"].(string)
r.mu.Lock()
w, ok := r.pending[corr]
delete(r.pending, corr)
r.mu.Unlock()
if ok {
w <- body
}
}
// Orphaned replies must not live forever.
r.rdb.Expire(ctx, r.replyStream, 5*time.Minute)
}
}
func (r *Requester) Call(ctx context.Context, body string) (string, error) {
if _, ok := ctx.Deadline(); !ok {
return "", errors.New("RPC requires a deadline")
}
id := uuid.NewString()
wait := make(chan string, 1)
r.mu.Lock()
r.pending[id] = wait
r.mu.Unlock()
defer func() {
r.mu.Lock()
delete(r.pending, id)
r.mu.Unlock()
}()
err := r.rdb.XAdd(ctx, &redis.XAddArgs{
Stream: requestStream,
MaxLen: 10000,
Approx: true,
Values: map[string]any{
"correlation_id": id,
"reply_to": r.replyStream,
"body": body,
},
}).Err()
if err != nil {
return "", err
}
select {
case v := <-wait:
return v, nil
case <-ctx.Done():
return "", ctx.Err()
}
}
// Serve is the replier: read as a group member, answer on the stream named in
// the request, then XACK the request.
// This sketch only consumes new entries. Add pending recovery (XAUTOCLAIM),
// stable logical deduplication, and atomic reply/expiry policy before production.
func Serve(ctx context.Context, rdb *redis.Client, consumer string) error {
err := rdb.XGroupCreateMkStream(ctx, requestStream, "repliers", "0").Err()
if err != nil && err.Error() != "BUSYGROUP Consumer Group name already exists" {
return err
}
for ctx.Err() == nil {
res, err := rdb.XReadGroup(ctx, &redis.XReadGroupArgs{
Group: "repliers",
Consumer: consumer,
Streams: []string{requestStream, ">"},
Count: 10,
Block: time.Second,
}).Result()
if err != nil {
if errors.Is(err, redis.Nil) {
continue
}
return err
}
for _, msg := range res[0].Messages {
replyTo, _ := msg.Values["reply_to"].(string)
corr, _ := msg.Values["correlation_id"].(string)
if !strings.HasPrefix(replyTo, "quotes:replies:") || corr == "" {
return errors.New("invalid reply address or correlation id")
}
answer := fmt.Sprintf("quote for %v", msg.Values["body"])
if err := rdb.XAdd(ctx, &redis.XAddArgs{
Stream: replyTo,
MaxLen: 1000,
Approx: true,
Values: map[string]any{"correlation_id": corr, "body": answer},
}).Err(); err != nil {
return err
}
if err := rdb.Expire(ctx, replyTo, 5*time.Minute).Err(); err != nil {
return err
}
if err := rdb.XAck(ctx, requestStream, "repliers", msg.ID).Err(); err != nil {
return err
}
}
}
return ctx.Err()
}
func main() {
addr := os.Getenv("REDIS_ADDR")
if addr == "" {
log.Fatal("set REDIS_ADDR, e.g. localhost:6379")
}
rdb := redis.NewClient(&redis.Options{Addr: addr})
r := NewRequester(rdb)
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
reply, err := r.Call(ctx, "A-1")
log.Printf("reply=%q err=%v", reply, err)
}In production systems
- RabbitMQ Direct Reply-To is documented with its own metric: replies dropped by the broker show up as
rabbitmq_global_messages_dead_lettered_maxlen_total{queue_type="rabbit_volatile_queue"}in Prometheus, and the pseudo-queue never appears inrabbitmqctl list_queues. The 4.4 page explains it is implemented by therabbit_volatile_queuetype: non-durable, unbuffered, at-most-once delivery that can drop replies. - RabbitMQ tutorial 6 (Go and PHP) is the reference RPC client: one callback queue per client, a correlation id per request, and an explicit list of what it leaves unsolved (no servers running, timeouts, error forwarding).
- Spring for Apache Kafka ships
ReplyingKafkaTemplatewithKafkaHeaders.CORRELATION_ID,REPLY_TOPICandREPLY_PARTITION, a default reply timeout of 5 seconds, and guidance to give each instance a uniquegroup.idor a dedicated partition: the industrial form of the Kafka pitfalls above. - HTTP APIs that start long operations use RFC 9110’s 202 semantics;
Locationis this API’s monitoring convention; the status monitor is the reply channel. Stripe's documented idempotency keys are the retry-safe form of the synchronous call. - Laravel Reverb and Broadcasting normally deliver
ShouldBroadcastthrough queued jobs (ShouldBroadcastNowis the synchronous exception): a worker outage silently delays every push reply. - W3C Trace Context is the cross-vendor format that tracers (OpenTelemetry and others) use to keep one trace across broker hops.
In architecture: from a single process to a distributed system
Monolith
One Laravel app, one database. A "reply" is a method return or dispatchSync: the call never leaves the process, so there is nothing to correlate. When one action is slow (PDF generation), use a queued job and a status row: the controller returns 202, the page polls GET /reports/{id} or listens on a Reverb channel. The concept of correlation id is the primary key of the status row. Avoid introducing RabbitMQ just to call a function in the same codebase.
1 POST /reports -> INSERT reports(state=queued) ; dispatch(...)->afterCommit() ; 202 Location
2 queue:work -> job builds PDF ; UPDATE reports SET state='done' ; event ReportReady
3 browser (poll or Echo) -> sees done ; downloadsModular monolith
Modules (Billing, Catalog) talk through an interface: PricingGateway::quote($sku): Money. Today the implementation is an in-process call to the Catalog module. Keep the interface synchronous only if a user waits; if a module needs "later", expose a command and let the result come back as an event. Because both modules share the process, you can start with dispatchSync, then switch the binding to a queued job plus a status row, by changing the contract to return an operation id or future. The trap: a module calling another through a queue and blocking on the answer, which keeps the modules coupled and adds a failure mode. Shared tables are acceptable for the status row if the owning module is explicit. See event-driven architecture.
Microservices
Checkout needs a price from Pricing. Option A: REST/gRPC with a 300 ms deadline, a circuit breaker, a cache of the last price, traceparent forwarded. Option B: Checkout publishes QuoteRequested and moves on; Pricing publishes QuoteReady (correlated by quote_id); Checkout's consumer updates the order and the browser is told over SSE. Option C (broker RPC): RabbitMQ with Direct Reply-To, deadline 500 ms, request TTL 500 ms, idempotent replier, bulkhead of 20 workers. Choose A when the user waits and Pricing is fast; B when the quote may take seconds or Pricing may be down; C only when the broker is already the platform's transport and you want its load balancing. Every hidden request-reply is a synchronous dependency in disguise: availability multiplies, latency adds, and a slow downstream empties the caller's worker pool. Messages that cross the boundary are integration events; the failure design is in designing for failure; transport choices are in service communication. Multi-step work belongs in a saga, where the saga, not a thread, waits.
1 browser -> checkout : POST /orders (Idempotency-Key k-9, traceparent T)
2 checkout -> DB : INSERT order(state=pending) + outbox row QuoteRequested(quote_id=q-1)
3 checkout -> browser : 202 Location /orders/o-1
4 outbox relay -> broker: QuoteRequested {quote_id: q-1, traceparent T}
5 pricing <- broker : consume, compute, INSERT processed_requests(q-1)
6 pricing -> broker : QuoteReady {quote_id: q-1, price}
7 checkout <- broker : consume (idempotent), UPDATE order ; push SSE to browserDistributed data
Several things break at scale. Replica lag: the status resource read from a replica may say queued after the worker wrote done on the primary; send the first poll to the primary or carry a version (see replication & failover). Cluster boundaries: a RabbitMQ requester and replier may sit on different nodes; Direct Reply-To works across nodes but the reply is still not durable, and quorum queues for requests add a consensus round trip (distributed SQL & consensus for the idea). Multi-region: a request-reply across regions adds at least one cross-region round trip (outbound and return legs), plus broker/consensus hops and fails whole when the link flaps; keep replies regional and replicate state, not calls. Push fan-out: with several web nodes, an SSE or WebSocket connection lives on one node, so the result must reach that node through a backplane (Redis Pub/Sub, broker fan-out). Clocks: TTLs and deadlines compare clocks on different machines; use relative queue TTL for retention and an explicit execution deadline with monitored clock skew; neither cancels already committed side effects. Idempotency across regions: the dedup table must be in the same consistency domain as the effect.
Scaling path
| Load | Design | What changes |
|---|---|---|
| 1x: tens of calls per second | REST/gRPC with deadlines; or queued job + status row | One reply path; nothing clever |
| 10x: hundreds per second | Competing repliers; request TTL; bulkhead; per-client reply queue; SSE for live results | Starvation becomes visible; add 202 where users wait |
| 100x: thousands per second, many clients | Direct Reply-To for churny clients; reply streams or partitions per instance; backplane for push; sharded status table | Reply-queue count and connection churn dominate; metrics for dropped direct replies; reconciliation sweeps |
| Multi-region | Regional replier pools; replicate state; fail whole calls fast | Cross-region request-reply avoided |
Lab
Setup (commands only; nothing here starts a broker for you). The starvation demo needs only Go. The RPC latency comparison needs RabbitMQ and an HTTP service; both are labelled "expected, not run".
cd docs/snippets/messaging/request-reply-rest-amqp/go
go run ./starvation -mode sync # 8 web workers block on a 20 jobs/s back-end
go run ./starvation -mode 202 # same load, workers return at onceStarvation model — expected, not run. The program offers roughly 100 requests/s for 1.5 seconds to eight web slots and a backend limited to 20 jobs/s. With blocking RPC, expect occupied slots, reply timeouts and rejected callers; a health probe competing for those slots should also wait. With immediate 202 responses, expect shorter front-door occupancy but a growing accepted-work backlog. Exact request counts and percentiles depend on scheduling; record your own results rather than treating a sample number as a benchmark.
The 202 shape still needs an admission limit: once backlog or expected wait exceeds policy, reject new work (429/503) instead of accepting an unbounded queue. A successful HTTP acceptance is not a completed business operation.
| # | Experiment | Command (sketch) | Expected, not run |
|---|---|---|---|
| 1 | HTTP baseline | hey -z 30s -c 50 http://pricing.local/quotes/A-1 | Measure the baseline on the actual environment; no universal millisecond target |
| 2 | RabbitMQ RPC, exclusive reply queue (tutorial 6 client) | Go client, 50 goroutines, 30 s | p50 a small number of ms above HTTP (two broker hops); p99 wider; one queue per client visible in rabbitmqctl list_queues |
| 3 | RabbitMQ RPC, Direct Reply-To (go run ./after/rabbitmq) | same load | Similar p50 to experiment 2; no reply queue in list_queues; metric rabbitmq_global_messages_delivered_total{queue_type="rabbit_volatile_queue"} rises |
| 4 | Kill the requester mid-call | kill -9 the client | Experiment 2: reply queue deleted; replier logs basic.return with mandatory. Experiment 3: reply dropped; ..._dead_lettered_maxlen_total{queue_type="rabbit_volatile_queue"} rises |
| 5 | Slow replier (sleep 3 s), caller deadline 2 s | edit the replier | Caller times out at 2 s; reply arrives at 3 s and is dropped as an orphan; with request TTL 2000 ms the queued request never reaches the replier if it was still waiting |
| 6 | Crash the replier before ack | kill -9 after publish, before ack | Request redelivered; second reply with the same correlation_id; requester ignores it; effect twice without a dedup row |
| 7 | 202 + status vs blocking handler at 100 rps | Laravel DispatchModes::blocking vs After | Blocking: FPM workers exhausted, /health stalls. 202: handler returns in milliseconds |
# expected, not run: shape of the latency table (classes, not numbers)
transport p50 p99 reply queues survives requester restart
http (keep-alive) lowest low none n/a
rabbit rpc, exclusive queue low medium 1 per client no
rabbit rpc, direct reply-to low medium 0 no (dropped)
rabbit rpc, long-lived queue low medium 1 per client yes
kafka rpc (reply partition) higher high 0 yes, until retentionRecord: p50 and p99 latency per transport, count of orphan replies, count of duplicate replies, number of reply queues, and what /health did during the blocking test.
Common misconceptions
| Belief | Reality |
|---|---|
| "A queue between two services makes the call asynchronous" | Only if the caller stops waiting; otherwise it is a synchronous call with an extra hop |
| "A correlation id makes the call safe to retry" | It matches replies to requests; retries need idempotency |
| "Direct Reply-To is just a faster reply queue" | No buffering, at-most-once, one channel; it is a different guarantee |
| "If the caller times out the work is cancelled" | Nothing cancels it; use a request TTL and an idempotent replier |
"202 means the work will succeed" | RFC 9110: it might never be acted upon; the status resource must show failure |
| "Every reply that arrives is for me" | Late and duplicate replies are normal; drop unknown ids |
| "Kafka can do request-reply as well as RabbitMQ" | It can, with headers and a reply partition, at higher latency and complexity |
| "Redis Pub/Sub is a reliable reply channel" | At-most-once; a reply before the subscription is lost |
| "The trace id is the correlation id" | Different scope: a trace spans many pairs; a correlation id matches one pair |
| "gRPC replaces messaging" | It is a synchronous RPC framework; it shares REST's coupling in time |
| "SSE or WebSocket makes the reply reliable" | Push is at-most-once to whoever is connected; the status resource stays the source of truth |
"Laravel dispatch() can return the job's result" | It returns dispatch metadata/a pending dispatch object, not the asynchronous result; use a row, cache key or broadcast |
Cheat sheet
| Topic | What to remember |
|---|---|
| Pattern | Request-Reply = two messages on two channels; Return Address says where, Correlation Identifier says which |
| Correlation id | Requestor generates it, replier copies it unchanged; unknown id means drop |
| Reply queue | One per client (exclusive or long-lived), not one per call |
| Direct Reply-To | amq.rabbitmq.reply-to, no-ack, same channel, one consumer per channel, at-most-once |
| Timeouts | Caller deadline plus request TTL; nothing cancels the work |
| Orphans | Late replies are normal; delete the pending entry on timeout |
| Duplicates | Redelivery after a missed ack; make the replier idempotent |
| Sync over async | Publishing then blocking ties a worker to the replier's latency; avoid |
| 202 | Accepted, not done; Location + status resource that can say failed |
| Push | SSE or WebSocket: subscribe first, then reconcile durable status; webhook with Idempotency-Key |
| Trace | Propagate traceparent in headers; do not reuse correlation_id as a trace id |
| Kafka | No reply-to: headers, reply partition or unique group.id, short retention.ms, deadline in code |
| Redis | Subscribe before request for Pub/Sub; tail reply streams by last id; EXPIRE the key |
| Laravel | Row + afterCommit() + broadcast/notification; Http with timeout and key; replier is a custom command |
| Rule | "When in doubt avoid RPC" (RabbitMQ tutorial 6); use REST when the caller must wait |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Name the three EIP patterns that together make request-reply work and what each one adds. Important
Answer
Answer: Request-Reply (two messages on two channels), Return Address (the request names where to reply), Correlation Identifier (the reply carries the request's id).
2 — A client sends five requests quickly over one reply queue. Why can replies arrive in a different order, and what lets the client cope? Must-know
Answer
Answer: Repliers take different times and competing consumers finish out of order. The client's pending table maps each correlation_id to its waiter.
3 — List four documented limits of RabbitMQ Direct Reply-To. Good to know
Answer
Answer: No-ack consumption only; same connection and channel for consuming and publishing; one consumer per channel; at-most-once and dropped if the requester disconnects; invisible in list_queues; not for hundreds of replies per second to one requester.
4 — A caller times out at 2 s and the replier answers at 3 s. What happens, and which two settings reduce the waste? Important
Answer
Answer: The reply arrives with an unknown id and is dropped. A request TTL of about 2 s removes a request that has not yet been picked up; a replier-side deadline check skips work for expired requests.
5 — Why does a duplicate reply appear, and where must it be handled? Must-know
Answer
Answer: The replier crashed after publishing the reply but before acking the request, so the request is redelivered. The requestor ignores the second reply (entry already deleted); the replier needs an idempotent effect or a dedup row.
6 — Explain why sync over async exhausts a web server even though a queue sits in the middle. Must-know
Answer
Answer: Each handler holds a worker while it waits, so the pool size becomes the throughput ceiling, and the back-end's latency becomes the front door's latency. The queue buffers the back-end's work but not the callers' wait.
7 — What must a 202 response contain, and what must the status resource be able to say? Must-know
Answer
Answer: A description of the current status, a pointer (Location) to a status monitor, optionally Retry-After. The status resource must be able to report failure because "the request might or might not eventually be acted upon".
8 — Why are correlation_id and traceparent both needed? Important
Answer
Answer: The correlation id matches one reply to one request. The trace context stitches many hops of one user action into a single trace and changes its parent id per hop.
9 — Give three reasons request-reply on Kafka is awkward. Important
Answer
Answer: No per-client queue or reply-to (every instance can read the reply topic, or you give each a partition or topic); group rebalances delay a new requester; replies are retained, not removed; no per-message TTL.
10 — When is REST or gRPC simply the right answer? Must-know
Answer
Answer: When the caller must have the answer to continue, the work is fast, and a failure should surface at once: a price, a permission check, a validation. Add a deadline, bounded retries on idempotent calls and an idempotency key for POST.
11 — Why subscribe before publishing when you use Redis Pub/Sub for a reply? Important
Answer
Answer: Pub/Sub keeps nothing: a message published before the subscription is active is lost ("forever lost" if the subscriber cannot handle it).
12 — In Laravel, why use afterCommit() on the job and ShouldDispatchAfterCommit on the event? Important
Answer
Answer: So the worker and listener cannot act before the status row commits. This orders dispatch but does not close the database-to-broker crash gap; use an outbox for durable acceptance.
Glossary
| Term | One line |
|---|---|
| Request-Reply | EIP pattern: a request message and a reply message on two channels |
| Requestor / Replier | The asking side and the answering side |
Return Address (reply_to) | Request property naming where to send the reply |
Correlation Identifier (correlation_id) | Id copied from request to reply to match them |
Message id (message_id) | Identity of one message, for dedup and logs |
| Pending table | Requestor's map from correlation id to waiter |
| Synchronous Block | EIP: one thread sends and blocks for the reply |
| Asynchronous Callback | EIP: a listener thread completes callbacks; many calls share one reply channel |
| Reply queue | Queue that holds replies for one requestor |
| Exclusive queue | Queue usable by one connection, deleted when it closes |
| Auto-delete queue | Queue deleted when its last consumer cancels |
Direct Reply-To (amq.rabbitmq.reply-to) | RabbitMQ pseudo-queue: replies go straight to the requester's channel, at-most-once |
rabbit_volatile_queue | Internal queue type behind Direct Reply-To: non-durable, zero-buffer, may drop |
mandatory / basic.return | Publish flag and the notice returned when a message cannot be routed |
Prefetch (basic.qos) | Unacked messages a consumer may hold; 1 for fair RPC workers |
Per-message TTL (expiration) | Time a message may wait in a queue before it is dropped or dead-lettered |
| Orphaned reply | A reply whose request is no longer waiting |
| Sync over async | Publishing to a queue and then blocking for the reply |
| Bulkhead | Separate, bounded worker pool so one slow dependency cannot take everything |
202 Accepted | HTTP status: accepted for processing, not complete |
| Status resource / status monitor | Resource that reports the progress and result of an accepted request |
Retry-After | Header telling a client when to ask again |
Idempotency-Key | Request header (IETF draft) identifying a logical request so retries are safe |
| SSE (Server-Sent Events) | One-way server-to-browser stream over HTTP (text/event-stream) |
| WebSocket / Reverb | Two-way connection; Reverb is Laravel's first-party WebSocket server |
| Webhook | Server-to-server HTTP callback carrying a result |
traceparent | W3C Trace Context header: version, trace-id, parent-id, flags |
tracestate | Vendor-specific companion of traceparent |
ReplyingKafkaTemplate | Spring for Apache Kafka helper implementing request-reply over Kafka |
| Reply partition | Kafka partition reserved for one requester's replies |
retention.ms | Kafka topic setting: how long records are kept |
ManualPartitioner | franz-go partitioner that sends a record to the partition set on it |
| Scatter-gather | One request, many repliers, one aggregated result |
| Backplane | Shared channel (Redis, broker) that carries push events to the web node holding the connection |
References
Hohpe & Woolf, Enterprise Integration Patterns: Request-Reply, Return Address, Correlation Identifier
RabbitMQ: Direct Reply-To, RPC tutorial (Go), RPC tutorial (PHP), Consumers, TTL
IETF: RFC 9110, HTTP Semantics, section 15.3.3 "202 Accepted" and section 9.2.2 "Idempotent Methods"; Idempotency-Key header (Internet-Draft)
W3C: Trace Context
Apache Kafka: KIP-82 Add Record Headers, Design, Topic configs; Spring for Apache Kafka: Sending messages, ReplyingKafkaTemplate
Stripe: Idempotent requests
gRPC: Introduction
Laravel 13: Queues, HTTP Client, Broadcasting, Reverb, Events, Notifications, Redis
Clients: amqp091-go, franz-go kgo, go-redis, php-amqplib, laravel-queue-rabbitmq, laravel-kafka
NATS: Request-Reply semantics; Laravel source: Dispatchable.
RabbitMQ: Publisher confirms; Redis: XREADGROUP.