Columns › 3. Splitting into microservices › Part 10
REST, gRPC, WebSocket or Webhook: Which Fits Where
REST、gRPC、WebSocket 與 Webhook 怎麼選:各自適合的場景
Once services are split, every connection needs a way to talk. Using a few questions (who speaks first, must the caller wait, one-way or two-way, who is on the other end) this article compares REST, gRPC, SSE, WebSocket, webhooks and message queues, says where each fits and where it does not, and implements in Go a webhook receiver with signatures, replay protection and deduplication, plus an SSE stream for order status.
In this article
- What this article solves
- Step 1: Describe the shape of the connection
- Step 2: REST: the default for the public and for browsers
- Step 3: gRPC: synchronous calls between services
- Step 4: One-way push: polling, long polling and SSE
- Step 5: WebSocket: when you really need two-way traffic
- Step 6: Webhooks: receiving notifications from an external system
- Step 7: Sending webhooks: the shop notifying merchants
- Step 8: Asynchronous work inside: message queues
- Step 9: One table and a decision flow
- Step 10: Back to the shop: the choice on each edge
- Common pitfalls
- Key takeaways
- References
- Next
The previous article, “When to Split: Service Boundaries and Decomposition Strategies”, organised the shop into a few clearly bounded modules, order, payment and inventory, and decided which to move out first. As soon as the boundaries are drawn, the next question arrives: between these services, between services and browsers, and between services and outside companies, how should they talk? This article does not rush into the details of any one protocol. It first builds a way of deciding, so that every connection gets a choice you can justify.
What this article solves
After the split, communication in example.com/shop suddenly takes several shapes:
- Browsers and the mobile app look up products and place orders.
api-gatewayreceives an order and has to callorder;orderhas to askinventorywhether there is stock.- After the user pays, the payment provider (another company) has to tell
paymentthat the payment succeeded. - The user sits on a "payment processing" page and wants to see the status the moment it changes, not keep pressing reload.
- Merchants on the platform want their own shipping systems to be told immediately when an order is placed.
- After a successful payment, sending email, awarding points and updating reports are things the user should not wait for.
A common mistake is to pick a "favourite" style and apply it to every line: everything in REST, and payment status can only be found by the front end polling every second; everything in gRPC, and browsers cannot connect; WebSocket sounds real-time, so a page that only needs one-way notifications becomes a two-way long-lived connection, and most of the effort goes into connection management. None of these styles is more advanced than the others. They solve problems of different shapes.
This article covers, in order:
- A few questions that describe the shape of a connection.
- REST: resources, methods, status codes, caching, idempotency keys, versioning and pagination, and where it fits and does not.
- gRPC: synchronous service-to-service calls, and how browsers can reach them.
- One-way push: short polling, long polling and Server-Sent Events (SSE), with an SSE stream for order status in Go.
- WebSocket: when you really need two-way traffic, and the problems that come with scaling it.
- Webhooks: receiving notifications from an external system, with signature checks, replay protection, deduplication and a fast response in Go.
- Sending webhooks: what the sender owes when the shop notifies merchants.
- Asynchronous work inside: when to switch to a message queue.
- One summary table and one decision flow.
- Back to the shop: what each edge uses, and why.
Step 1: Describe the shape of the connection
Before choosing a style, answer a few questions about this particular connection. The answers settle most of the choice; the protocol itself is the last thing to decide.
Figure: the initiating side is on top. REST and gRPC are started by the caller, one request and one response; with SSE the browser subscribes and the server then pushes one way; with WebSocket both sides can send once connected; a webhook is a POST that the event source sends to another server on its own.
The first question can be read straight off the figure: who speaks first. REST and gRPC both work as "someone asks, then someone answers"; the server cannot tell you anything unprompted. With SSE and WebSocket the browser opens the connection, but once it is open the server can send events as they happen (the thick lines). Webhooks are the odd one out: the event source itself initiates, and the receiver just exposes a URL and waits.
| Question | What to ask | What it decides |
|---|---|---|
| Who speaks first | Does the caller need data, or does the event source need to tell someone? | Request/response or push |
| Must the caller wait | Can the caller carry on before it has the result? | Synchronous call or message queue |
| Direction and rate | Only one side sends? Both send often? One response or a stream? | Unary call, stream, SSE or WebSocket |
| Who is on the other end | A browser, a mobile app, outside developers, another company, or your own service? | Usable protocols, how stable the contract must be, security |
| Contract and coupling | Can both sides release together? Is the contract generated code or a document? | protobuf or JSON, versioning |
| Latency and volume | How many calls per second, how big, how tight the latency? | Binary or text format, connection reuse |
| Tooling and observability | When it breaks, can curl, browser dev tools or the logs explain it? | Cost of debugging |
| Network path | Which proxies, load balancers and corporate firewalls sit in between? | Whether HTTP/2, long-lived connections and idle timeouts get blocked or cut |
The last two rows are the ones most often ignored. A protocol that wins a benchmark does not necessarily win "behind the customer's corporate proxy" or "at three in the morning, working out what happened from the logs". This is especially true for external connections: you control neither the other side's network nor the tools their engineers have.
Step 2: REST: the default for the public and for browsers
In practice REST usually means "a resource-oriented HTTP + JSON API": the URL names a resource, the HTTP method names the action, and the status code gives the outcome. It is not the fastest, but it is the one everybody can use: browsers support it natively, every language has an HTTP client, one line of curl tests it, CDNs and proxies understand its caching rules, and outside developers need no extra tooling.
Figure: 1. create an order with an idempotency key and get 201 with the new resource's location; 2. after a dropped connection, resend with the same key and get the same order; 3. fetch with If-None-Match and get 304 with no body if nothing changed; 4. list orders with cursor pagination.
The figure puts together the conventions a good REST API needs. Read it in order:
1. Methods and status codes must tell the truth. POST /v1/orders creates an order; on success it returns 201 Created with the new resource's URL in the Location header. Common methods and their meaning:
| Method | Use | Safe (no change) | Idempotent (repeat gives same result) |
|---|---|---|---|
GET | Read | Yes | Yes |
PUT | Replace entirely | No | Yes |
DELETE | Delete | No | Yes |
POST | Create, or perform an action | No | No |
PATCH | Partial update | No | Not guaranteed |
Status codes let the caller decide what to do next without parsing the body: 400 for a malformed request, 401 for missing or invalid credentials, 403 for an identity without permission, 404 for a missing resource, 409 for a conflict with the current state (paying for a cancelled order, say), 422 is often used for a well-formed request that a business rule forbids, 429 for rate limiting together with Retry-After, and 5xx for server problems. Use one consistent error body; Problem Details from RFC 9457 (application/problem+json) is a ready-made choice.
2. A POST that changes data must be safe to resend. When a mobile connection drops between "request sent" and "response received", the app does not know whether the order was created. The fix is for the client to generate an idempotency key and send it in an Idempotency-Key header (the header name is currently an IETF draft, but widely used); the server remembers which result belongs to which key and returns the same result on a resend. The implementation is in “Idempotency and Distributed Locks”.
3. Caching and conditional requests come free with HTTP. A response carries an ETag (an identifier for the resource's version); next time the client sends If-None-Match, and if nothing changed it gets 304 without the body. An update sends If-Match, and a version mismatch returns 412 Precondition Failed, which is optimistic locking out of the box. Add Cache-Control to public data that is the same for every user (the product catalogue) and a CDN absorbs most of the traffic. Neither gRPC nor WebSocket has this machinery ready to use.
4. Lists must be paginated, and versioning should be planned early. For large lists use a cursor ("start after the last item I saw") rather than offset, because OFFSET 100000 makes the database scan a hundred thousand rows only to throw them away, and rows added or removed while paging cause duplicates or gaps. The most common versioning approach puts the version in the path (/v1/): adding fields without changing the meaning of existing ones needs no new version; only a genuinely breaking change opens /v2/, and both versions run side by side for a while.
Where it fits: public APIs, browsers and mobile apps calling the back end, interfaces for outside developers to integrate with, and read-heavy data that benefits from caching. In the shop, every call from the browser and the app to api-gateway is REST; the gateway's routing, authentication and rate limiting are in “Building an API Gateway in Go: Routing, Authentication and Rate Limiting”.
Why: the other side is a client you do not control, so reach and debuggability matter more than performance. Outside developers can connect with any language and any tool; when something breaks, one line of curl reproduces it.
When not to use it:
- The server needs to notify first: REST can only wait to be asked; "know as soon as the status changes" means polling, see Step 4.
- High-frequency internal calls that need a strict contract: JSON has no enforced types, a renamed field is only discovered at run time, and every service writes its own serialisation and error mapping. That is gRPC's home ground, next step.
- One screen needs ten resources: the front end makes ten requests or asks the back end for a pile of custom endpoints. Then consider an aggregating endpoint behind the gateway (Backend for Frontend), or evaluate GraphQL; both are outside the scope of this article.
Step 3: gRPC: synchronous calls between services
gRPC defines services and messages in a .proto file and generates code for both sides; transport is HTTP/2 and messages use the Protocol Buffers binary format. For internal services it turns what REST leaves to "agreement" into "standard":
- The contract is code: field types live in the
.proto, so ifordercallsinventorywith the wrong arguments, the build fails; field-number rules let old and new versions coexist. - Deadlines travel along the call chain: the time the caller has left is sent to the server, and when the server calls further downstream it shares the same budget automatically.
- Standard status codes:
NotFound,FailedPrecondition,Unavailable,DeadlineExceededand so on; the caller decides whether to retry from the code, instead of each service inventing its own. - Four call types: unary (one request, one response), server streaming, client streaming and bidirectional streaming.
- Efficiency: the binary encoding is smaller and faster to parse than JSON; HTTP/2 multiplexes many requests on one connection.
Where it fits: calls inside one organisation, service to service, where the caller must wait for the result before carrying on. In the shop, api-gateway calling order, payment and inventory, and order reserving stock with inventory while placing an order, are all gRPC.
Why: both sides of an internal call are in your hands, so you can generate code together and release together; a strict contract and deadline propagation are worth far more than the inconvenience of not being able to hit it with plain curl.
When not to use it:
- Browsers calling directly: a browser's
fetchcannot fully control HTTP/2 frames, and cannot read the HTTP trailers where gRPC puts its status, so a browser cannot speak native gRPC. To let browsers call gRPC services there are three routes: use the gRPC-Web protocol with a translating proxy in front (for example Envoy's gRPC-Web filter); use Connect (connectrpc.com/connect), where one server supports gRPC, gRPC-Web and its own Connect protocol, which carries JSON or protobuf over ordinary HTTP; or use grpc-gateway, which generates a REST JSON reverse proxy from HTTP annotations in the proto, so the outside still sees REST. - Exposing it to outside developers: asking them to install
protocand generate code before they can try your API is a much higher bar than REST. The usual approach is gRPC inside, with the gateway exposing REST. - The caller does not need to wait: sending email or updating reports should not hold up an order; that is a job for a message queue (Step 8).
- The network path cannot carry HTTP/2 end to end: some proxies and older load balancers downgrade HTTP/2 to HTTP/1.1, and gRPC will not get through. gRPC's long-lived connections also mean an L4 load balancer only spreads traffic to whichever instance was first connected to; “Service Discovery and Load Balancing for Go Microservices” deals with that.
If you decide to expose the same service as REST with grpc-gateway, the proto gains an HTTP mapping:
// fragment: google.api.http annotation, from which grpc-gateway generates REST routes
import "google/api/annotations.proto";
service OrderService {
rpc GetOrder(GetOrderRequest) returns (Order) {
option (google.api.http) = {
get: "/v1/orders/{order_id}"
};
}
}How to design the proto contract, generate the code and write deadlines and interceptors is the subject of the next article. Here, just remember its place: internal, synchronous, strict contract.
Step 4: One-way push: polling, long polling and SSE
Back to the "payment processing" page. After paying at the payment provider, the user is sent back to the shop; at that moment payment may not yet have received the webhook with the result, and the order is still pending. The page should update the moment the status becomes paid. Data flows in one direction only: server to browser.
Figure: each box is one HTTP request, and dark boxes are responses that carry an event. With short polling most responses are empty, and an event is only discovered at the next poll; with long polling each request is held and answered as soon as an event happens; with SSE one connection stays open and events go straight down it.
Read the figure from top to bottom:
- Short polling: the front end sends
GET /v1/orders/A-1001every few seconds. It is the simplest to build, using the REST from Step 2; the cost is that most requests are empty, and the worst-case delay is a whole interval (in the figure, an event is only noticed at the next box). Fits: rare updates, tolerant latency and few users, such as an admin report refreshed every thirty seconds. - Long polling: the server receives a request and does not answer until there is new data or a timeout (say twenty-five seconds); the front end immediately asks again. Latency is close to real time, and it uses only ordinary HTTP, so it passes any proxy. Fits: real-time needs in restrictive networks that only allow plain HTTP requests. The downside is a fresh request per event, and the server holds resources for every waiting request.
- SSE (Server-Sent Events): the browser makes a GET with
EventSource; the server answers withContent-Type: text/event-streamand does not finish the response, writing a chunk of text whenever there is an event. It is still an ordinary HTTP response, so authentication, cookies, the gateway and logging all work as before; the browser reconnects automatically after a drop and sends the last event ID it received in theLast-Event-IDheader, so the server can resume from there.
The SSE format is plain text. Each event is a few field: value lines ended by a blank line; a line starting with a colon is a comment the front end never sees, which makes it a handy heartbeat:
id: 4
event: status
data: {"seq":4,"status":"paid"}
: ping
In Go, SSE is just a handler that is in no hurry to return. Here is order pushing order status (in practice the endpoint sits behind the gateway's routes):
package order
import (
"context"
"encoding/json"
"fmt"
"net/http"
"strconv"
"time"
)
// StatusEvent is one order status change; Seq increases per order and serves as the SSE event ID.
type StatusEvent struct {
Seq int64 `json:"seq"`
Status string `json:"status"`
}
// Watcher returns an order's status changes after afterSeq (missed ones first, then live ones);
// it closes the channel when ctx ends. In practice: a NATS subscription plus a database query to catch up.
type Watcher interface {
Watch(ctx context.Context, orderID string, afterSeq int64) <-chan StatusEvent
}
func final(s string) bool { return s == "paid" || s == "cancelled" }
// StatusStream pushes order status to the browser with Server-Sent Events.
// Route: mux.Handle("GET /orders/{id}/events", StatusStream(watcher, 15*time.Second))
func StatusStream(watcher Watcher, heartbeat time.Duration) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
orderID := r.PathValue("id")
// Authorisation goes here: check the order belongs to the signed-in user (omitted in this example)
after, _ := strconv.ParseInt(r.Header.Get("Last-Event-ID"), 10, 64) // sent by the browser automatically on reconnect
rc := http.NewResponseController(w)
_ = rc.SetWriteDeadline(time.Time{}) // long-lived response: lift http.Server's WriteTimeout
h := w.Header()
h.Set("Content-Type", "text/event-stream")
h.Set("Cache-Control", "no-cache")
h.Set("X-Accel-Buffering", "no") // ask nginx not to buffer this response
w.WriteHeader(http.StatusOK)
if err := rc.Flush(); err != nil {
return
}
events := watcher.Watch(r.Context(), orderID, after)
tick := time.NewTicker(heartbeat)
defer tick.Stop()
for {
select {
case <-r.Context().Done(): // the browser closed the tab or disconnected
return
case <-tick.C:
fmt.Fprint(w, ": ping\n\n") // comment line: keeps the connection alive, fires no event in the browser
case ev, ok := <-events:
if !ok {
return
}
data, err := json.Marshal(ev)
if err != nil {
return
}
fmt.Fprintf(w, "id: %d\nevent: status\ndata: %s\n\n", ev.Seq, data)
if final(ev.Status) {
_ = rc.Flush()
return // final state: the browser calls close() and does not reconnect
}
}
if err := rc.Flush(); err != nil {
return
}
}
})
}Points worth noticing:
http.ResponseController(since Go 1.20) lets usFlusheven through a wrappedResponseWriter, andSetWriteDeadline(time.Time{})lifts thehttp.Server'sWriteTimeout. “net/http and Middleware in Go” recommends settingWriteTimeouton the server, which is right for ordinary requests but would cut a long-lived response when it expires, so we lift it only inside this handler.- Heartbeats: send a comment line regularly. Many load balancers and proxies cut connections that carry no data for a while; a heartbeat keeps it alive and lets the server notice early that the other side has gone (the write fails).
- Proxy buffering: nginx buffers upstream responses by default, and events get stuck inside nginx. The response header
X-Accel-Buffering: noturns buffering off for this response; alternatively setproxy_buffering off;in that nginx location. - Reconnect and catch-up: when
WatcherreceivesafterSeqit must first query the database for missed changes, then switch to the live subscription. Use a per-order increasing sequence number as the event ID, not a timestamp, so catch-up is exact. - End after the final state: when the order reaches
paidorcancelledthe response ends. Note thatEventSourcereconnects automatically by default when the connection ends, so the front end must callclose()itself on the final state.
The front end needs only a few lines:
// Same-origin requests send cookies automatically; EventSource cannot set an Authorization header
const es = new EventSource(`/v1/orders/${orderId}/events`);
es.addEventListener('status', (e) => {
const ev = JSON.parse(e.data);
renderStatus(ev.status);
if (ev.status === 'paid' || ev.status === 'cancelled') es.close();
});The test starts a real server with httptest.NewServer and reads the stream with an ordinary HTTP client, checking the format, that Last-Event-ID is passed through, and that nothing is sent after the final state:
package order
import (
"bufio"
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
type fakeWatcher struct {
gotAfter int64
events []StatusEvent
}
func (f *fakeWatcher) Watch(ctx context.Context, _ string, afterSeq int64) <-chan StatusEvent {
f.gotAfter = afterSeq
ch := make(chan StatusEvent)
go func() {
defer close(ch)
for _, ev := range f.events {
select {
case ch <- ev:
case <-ctx.Done():
return
}
}
}()
return ch
}
func TestStatusStream(t *testing.T) {
fw := &fakeWatcher{events: []StatusEvent{{Seq: 3, Status: "pending"}, {Seq: 4, Status: "paid"}, {Seq: 5, Status: "never-sent"}}}
mux := http.NewServeMux()
mux.Handle("GET /orders/{id}/events", StatusStream(fw, time.Hour))
srv := httptest.NewServer(mux)
defer srv.Close()
req, _ := http.NewRequest(http.MethodGet, srv.URL+"/orders/A-1001/events", nil)
req.Header.Set("Last-Event-ID", "2")
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
if ct := resp.Header.Get("Content-Type"); ct != "text/event-stream" {
t.Errorf("Content-Type = %q", ct)
}
var lines []string
sc := bufio.NewScanner(resp.Body)
for sc.Scan() { // the server ends the response after the final state, so this reaches EOF
lines = append(lines, sc.Text())
}
got := strings.Join(lines, "\n")
want := "id: 3\nevent: status\ndata: {\"seq\":3,\"status\":\"pending\"}\n\n" +
"id: 4\nevent: status\ndata: {\"seq\":4,\"status\":\"paid\"}\n"
if got != want {
t.Errorf("stream =\n%s\nwant\n%s", got, want)
}
if fw.gotAfter != 2 {
t.Errorf("afterSeq = %d, want 2", fw.gotAfter)
}
}When SSE does not fit:
- The browser also sends often: SSE is downstream only. For the occasional upload, send a separate REST request; if both directions are busy (chat, collaborative editing), switch to WebSocket.
- Binary data: SSE carries text only; binary has to be encoded first.
- Many tabs over HTTP/1.1: browsers limit HTTP/1.1 connections per domain (commonly 6), and every tab with an open SSE stream uses one, so other requests start queueing. Over HTTP/2 the streams share one connection and the problem mostly disappears.
- Authentication only via cookies or the URL:
EventSourcecannot set headers. With cookies, keep the usual CSRF and origin checks; if you must use a token, put a short-lived, single-use ticket in the URL rather than a long-lived JWT, because URLs end up in access logs.
Step 5: WebSocket: when you really need two-way traffic
A WebSocket (RFC 6455) starts as an HTTP request: the client sends a GET with an Upgrade: websocket header, the server answers 101 Switching Protocols, and from then on that TCP connection is no longer HTTP but a channel where either side can send at any time, as text or binary messages.
Where it fits: interactions where both directions are busy and latency matters.
- Chat and customer support: the user sends messages while receiving the other side's messages and "typing" indicators.
- Collaborative editing: several people edit the same document; every keystroke's change goes out, and everyone else's changes must arrive at once.
- Live dashboards and trading screens: large, frequent updates, while the user switches what they are subscribed to.
- Online games: two-way synchronisation of positions and actions.
Why: with "SSE down, REST up", every upload is a complete HTTP request (headers, authentication, routing), which adds up at high frequency; a WebSocket is set up once, and each message then carries only a small frame overhead.
When not to use it: if the server only needs to notify one way (order status, for instance), SSE is simpler; for the occasional query, use REST. Once WebSocket is in production, you move from stateless requests to stateful connections, and all the problems below become yours.
Figure: a user connects through the load balancer to one WebSocket instance and the connection stays there. order publishes status changes to NATS; every instance subscribes to the same subject and forwards events to the connections it holds.
The figure shows the problems that appear when you scale:
- Connections live on one instance: user C's connection is on
ws-2, and onlyws-2can send to them. So an event cannot go to just "one" instance; it must fan out to every instance, and each instance decides whether it holds a relevant connection. The shop's events already flow through NATS JetStream; for live push, a plain NATS subscription is enough (push does not need persistence; what is missed is caught up on reconnect). - Uneven load: long-lived connections do not move when new instances appear. After scaling out, the old instances still carry most connections; when scaling in or deploying, every connection on the stopped instance drops at once.
- Idle timeouts: load balancers and proxies cut connections with no data for a while (an AWS ALB defaults to 60 seconds, and nginx's
proxy_read_timeoutalso defaults to 60 seconds). The WebSocket protocol has ping and pong control frames; the server sends pings at an interval shorter than those timeouts. Browsers answer pings automatically, but the browser's JavaScript API has no way to send a ping, so a client that wants to detect a dead connection must send its own application-level heartbeat. - Reconnect and catch-up: deployments and network changes (Wi-Fi to mobile data) drop connections. The client must reconnect automatically with backoff (plus random jitter, so everyone does not reconnect at the same moment) and send the last sequence number it received, so the server can resend what was missed. It is the same idea as SSE's
Last-Event-ID, except with WebSocket you build it yourself. - Authenticate on upgrade: the browser's
WebSocketAPI cannot set anAuthorizationheader. The common approach authenticates the upgrade request with a cookie, and then must check theOriginheader: otherwise a page on another site can open a WebSocket to your server using the user's cookie (cross-site WebSocket hijacking). The alternative is to exchange an ordinary REST call for a short-lived, single-use ticket and put it in the upgrade request's URL. A connection can last for hours, so the server must also be able to close it when the token expires or the user logs out. - Back-pressure: when a client's network is slow, messages for it pile up in server memory. Each connection's send buffer needs a limit; when it is full, drop messages that can be dropped (an outdated price update, say) or close that connection, so one slow client cannot take down a whole instance.
nginx does not forward the Upgrade header by default, so the location has to set it explicitly, with a read timeout longer than the heartbeat interval:
# fragment: nginx forwarding WebSocket
location /v1/ws/ {
proxy_pass http://ws_backend;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_read_timeout 120s;
}Go's standard library has no WebSocket server; the commonly used third-party packages are github.com/coder/websocket (formerly nhooyr.io/websocket) and github.com/gorilla/websocket. Whichever you pick, the problems above are for your code to handle; the package only takes care of the protocol. That is why the rule is use SSE first if SSE will do: for the same push, it has half the problems.
Step 6: Webhooks: receiving notifications from an external system
The payment provider is another company. It will never call you over gRPC or subscribe to your NATS, and you should not ask it "paid yet?" every few seconds. The standard practice is a webhook: you register a URL in the provider's dashboard (for example https://api.example.com/webhooks/payment), and when an event happens their server sends an HTTP POST to that URL with the event as the body.
Where it fits: server-to-server notifications across organisations, where the event source belongs to someone else. Payment results, completed refunds, shipping status and repository push events are all classic webhooks.
Why: whoever owns the event announces it. They know when it happens and you do not; polling wastes effort on both sides and is slower. And an HTTP POST is the only common language two companies can use without negotiating anything further.
When not to use it: when both ends are inside your organisation, a message queue (durable, replayable, with consumer groups) is much better than a webhook; and user devices (browsers, phones) cannot receive webhooks because they have no public URL. Also, a webhook is a notification, never the only source of truth: notifications can arrive late or get stuck on the sender's side, so important state must also be completed by active queries and reconciliation; see “Reconciliation: Matching Payment Provider Statements Reliably”.
The webhook URL is public, so anyone can send requests to it; and delivery is at-least-once, because the sender retries until it gets a 2xx. Those two facts decide what the receiver has to do:
Figure: on the left the sender signs id, timestamp and body and sends; on the right the receiver reads the raw body, checks the timestamp, compares the signature, deduplicates by id and stores in an inbox, then answers 200 at once, leaving the real work to a background worker; on a non-2xx answer or a timeout, the sender retries the same id with backoff.
Read down the right-hand side:
- Read the raw body, with a size limit. The signature is computed over bytes; parse the JSON and serialise it again, and whitespace or field order may differ so the signature fails.
- Check the timestamp. An attacker can record a legitimate request and send it again later (a replay). The signature alone cannot stop a replay, because the content is identical; rejecting timestamps outside the allowed window (five minutes either way here) shrinks the replay window to minutes.
- Compare the signature in constant time.
hmac.Equaltakes the same time however many leading bytes match, so an attacker cannot guess the signature byte by byte from response times. What is signed isid.timestamp.body: the three are bound together, so changing the id to dodge deduplication, or the timestamp to dodge the time check, breaks the signature. - Deduplicate by event id and store in the inbox. Within the five-minute window the same notification can still arrive twice (a sender retry, or an attacker replaying inside the window), so deduplicate by id. Deduplicating and storing are one action: the inbox table has the id as its primary key, and a successful insert means the first arrival.
- Answer 2xx at once, including for duplicates. Many senders treat no answer within a few seconds as a failure and retry; if the handler updates the order, sends email and calls other services synchronously, a little slowness triggers retries, and retries add load. So the handler only does "verify + store", and a background worker reading the inbox does the real processing.
At the bottom of the figure are the two failure branches: a failed check answers 401 (no point retrying; it will not pass); a failed store answers 5xx, so the sender retries later. The one thing you must never do is answer 2xx without storing the notification: that tells the sender "got it" and then loses it.
Here is the receiver in payment:
package webhook
import (
"context"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"io"
"net/http"
"strconv"
"time"
)
const (
maxBody = 1 << 20 // callback body limit: 1 MiB
tolerance = 5 * time.Minute // allowed clock skew for the timestamp
)
// Inbox stores notifications as received, for a background worker to process.
// Saving the same id a second time returns inserted=false (a unique constraint on the inbox table).
type Inbox interface {
Save(ctx context.Context, id string, body []byte) (inserted bool, err error)
}
// mac signs "id.timestamp.raw body": change any of them and the signature no longer matches.
func mac(secret []byte, id, ts string, body []byte) []byte {
m := hmac.New(sha256.New, secret)
m.Write([]byte(id + "." + ts + "."))
m.Write(body)
return m.Sum(nil)
}
// Sign produces the signature header value; shared by the sender and the tests.
func Sign(secret []byte, id, ts string, body []byte) string {
return hex.EncodeToString(mac(secret, id, ts, body))
}
// Receiver accepts pushed webhooks: verify, block replays, deduplicate, store, then answer 2xx at once.
type Receiver struct {
Secrets [][]byte // accept old and new keys during rotation
Inbox Inbox
Now func() time.Time
}
func (rc *Receiver) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Take the raw bytes first: the signature covers bytes, so never parse and re-serialise before checking
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxBody))
if err != nil {
http.Error(w, "body too large or unreadable", http.StatusBadRequest)
return
}
id := r.Header.Get("X-Webhook-Id")
ts := r.Header.Get("X-Webhook-Timestamp")
sec, err := strconv.ParseInt(ts, 10, 64)
if id == "" || err != nil {
http.Error(w, "missing id or timestamp", http.StatusBadRequest)
return
}
// Reject requests that are too old or too new: even with a valid signature they may be recorded replays
if d := rc.Now().Sub(time.Unix(sec, 0)); d > tolerance || d < -tolerance {
http.Error(w, "timestamp outside tolerance", http.StatusUnauthorized)
return
}
got, err := hex.DecodeString(r.Header.Get("X-Webhook-Signature"))
if err != nil || !rc.validSignature(got, id, ts, body) {
http.Error(w, "bad signature", http.StatusUnauthorized)
return
}
inserted, err := rc.Inbox.Save(r.Context(), id, body)
if err != nil {
// Not stored: answer 5xx so the sender retries later; never answer 2xx and lose the notification
http.Error(w, "try again later", http.StatusServiceUnavailable)
return
}
if !inserted {
// A resent or replayed notification we already have: still answer 2xx so the sender stops retrying
w.WriteHeader(http.StatusOK)
return
}
// The real work (updating the order, sending email) is done by a background worker reading the inbox
w.WriteHeader(http.StatusOK)
}
func (rc *Receiver) validSignature(got []byte, id, ts string, body []byte) bool {
for _, s := range rc.Secrets {
if hmac.Equal(got, mac(s, id, ts, body)) { // constant-time comparison against timing attacks
return true
}
}
return false
}Secrets is a slice because keys have to be rotated one day: during the rotation the sender may still sign with the old key, so accept both, and remove the old one once the switch is confirmed.
The test runs every attack and failure once, including "swap the id to dodge deduplication":
package webhook
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"sync"
"testing"
"time"
)
// memInbox is a test Inbox: a map stands in for the inbox table's unique constraint.
type memInbox struct {
mu sync.Mutex
seen map[string][]byte
fail bool
}
func (m *memInbox) Save(_ context.Context, id string, body []byte) (bool, error) {
m.mu.Lock()
defer m.mu.Unlock()
if m.fail {
return false, errors.New("db down")
}
if _, ok := m.seen[id]; ok {
return false, nil
}
m.seen[id] = body
return true, nil
}
func TestReceiver(t *testing.T) {
secret := []byte("whsec-test")
now := time.Unix(1_800_000_000, 0)
inbox := &memInbox{seen: map[string][]byte{}}
rc := &Receiver{Secrets: [][]byte{secret}, Inbox: inbox, Now: func() time.Time { return now }}
body := `{"payment_id":"pay_1","order_id":"A-1001","status":"succeeded","amount":129900}`
ts := strconv.FormatInt(now.Unix(), 10)
send := func(id, ts, sig, b string) int {
req := httptest.NewRequest(http.MethodPost, "/webhooks/payment", strings.NewReader(b))
req.Header.Set("X-Webhook-Id", id)
req.Header.Set("X-Webhook-Timestamp", ts)
req.Header.Set("X-Webhook-Signature", sig)
rec := httptest.NewRecorder()
rc.ServeHTTP(rec, req)
return rec.Code
}
valid := Sign(secret, "evt_1", ts, []byte(body))
old := strconv.FormatInt(now.Add(-time.Hour).Unix(), 10)
tests := []struct {
name string
id, ts, sig string
body string
want int
}{
{"valid notification", "evt_1", ts, valid, body, 200},
{"same one resent: still 200", "evt_1", ts, valid, body, 200},
{"wrong key", "evt_2", ts, Sign([]byte("wrong"), "evt_2", ts, []byte(body)), body, 401},
{"tampered body", "evt_1", ts, valid, strings.Replace(body, "129900", "1", 1), 401},
{"swapped id to dodge dedupe", "evt_9", ts, valid, body, 401},
{"request recorded an hour ago", "evt_3", old, Sign(secret, "evt_3", old, []byte(body)), body, 401},
{"signature not hex", "evt_4", ts, "zz", body, 401},
{"missing timestamp", "evt_5", "", valid, body, 400},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := send(tt.id, tt.ts, tt.sig, tt.body); got != tt.want {
t.Errorf("status = %d, want %d", got, tt.want)
}
})
}
if len(inbox.seen) != 1 {
t.Errorf("inbox has %d entries, want 1", len(inbox.seen))
}
inbox.fail = true
if got := send("evt_6", ts, Sign(secret, "evt_6", ts, []byte(body)), body); got != 503 {
t.Errorf("store failure: status = %d, want 503", got)
}
}
func TestKeyRotation(t *testing.T) {
oldKey, newKey := []byte("old"), []byte("new")
now := time.Unix(1_800_000_000, 0)
rc := &Receiver{Secrets: [][]byte{newKey, oldKey}, Inbox: &memInbox{seen: map[string][]byte{}}, Now: func() time.Time { return now }}
ts := strconv.FormatInt(now.Unix(), 10)
req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader("{}"))
req.Header.Set("X-Webhook-Id", "evt_1")
req.Header.Set("X-Webhook-Timestamp", ts)
req.Header.Set("X-Webhook-Signature", Sign(oldKey, "evt_1", ts, []byte("{}")))
rec := httptest.NewRecorder()
rc.ServeHTTP(rec, req)
if rec.Code != 200 {
t.Errorf("old key during rotation: status = %d, want 200", rec.Code)
}
}The background worker takes unprocessed notifications from the inbox with SELECT … FOR UPDATE SKIP LOCKED so several worker instances never take the same row, and sets processed_at when done. The processing must still be idempotent and decide through the state machine whether to update the payment, so a late or out-of-order notification cannot turn a succeeded payment back into processing; the details are in “Payment Pitfalls: Double Charges, Callbacks and Reconciliation”. That article's example stops at the signature and timestamp checks; this one adds deduplication by id, answering as soon as the notification is stored, and key rotation.
When integrating with a real payment provider, follow its documentation for the signature format, header names and allowed time window; there is usually an official library for verification too. The X-Webhook-* headers and hex encoding here are a format made up for the example. If you design outgoing webhooks of your own, the public Standard Webhooks specification is worth a look; it defines similar id, timestamp and signature headers.
Step 7: Sending webhooks: the shop notifying merchants
When the roles reverse, so do the duties. When the shop notifies a merchant's shipping system that an order was placed, order becomes the sender, and the sender has more to look after than the receiver:
- Write the event to an outbox first, then let a delivery worker send it. Calling the merchant's URL inside the order transaction means a slow or dead merchant server holds up ordering, and a rolled-back transaction leaves a notification already sent. Write the event with the outbox from “Distributed Transactions: Sagas and the Outbox Pattern”, and have a separate delivery worker send it.
- Every notification has a fixed id, set when written and unchanged on retry, so the receiver can deduplicate.
- Sign and include a timestamp, the same rules as the receiver in Step 6. Each merchant has its own key.
- Retries back off and have a limit. A merchant's server may be down for hours; start the interval at tens of seconds and double it, with random jitter, keep going for a while (a day, say), then mark the delivery failed and tell the merchant. It is the same principle as “Timeouts, Retries and Circuit Breakers”, with the timescale stretched from milliseconds to hours.
- Show the delivery log to the other side. Record the time, response code and duration of every attempt, show them in the merchant dashboard, and offer a "resend" button. When a merchant says "we never got it", both sides look at the same record.
- Disable endpoints that keep failing, so you do not retry forever against a URL that no longer exists; a
410 Goneanswer can disable it straight away. - Guard against SSRF: the webhook URL is entered by the merchant, which lets an outsider decide where your server connects. Someone may enter
http://169.254.169.254/(the cloud metadata service) or an internal service address. Allow onlyhttps, reject private, loopback and link-local addresses after resolving the name, and check again when actually connecting (checking only at registration is not enough; DNS answers can change later); ideally the delivery worker runs somewhere that cannot reach the internal network at all. - Set a timeout on every send, and limit how much of the response you read; a stuck merchant server must not hold up the whole delivery worker.
The code for one attempt and the backoff calculation:
package webhook
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"math/rand/v2"
"net/http"
"strconv"
"time"
)
// ErrGone means the receiver answered 410: the endpoint is retired, stop sending.
var ErrGone = errors.New("endpoint gone")
// Delivery is one notification for a merchant; its ID is fixed when written to the outbox and never changes on retry.
type Delivery struct {
ID string
URL string
Body []byte
}
// Attempt sends once. retry=true means it should be retried later.
func Attempt(ctx context.Context, c *http.Client, secret []byte, d Delivery, now time.Time) (retry bool, err error) {
ts := strconv.FormatInt(now.Unix(), 10)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, d.URL, bytes.NewReader(d.Body))
if err != nil {
return false, err // the URL itself is broken; retrying will not help
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Webhook-Id", d.ID)
req.Header.Set("X-Webhook-Timestamp", ts)
req.Header.Set("X-Webhook-Signature", Sign(secret, d.ID, ts, d.Body))
resp, err := c.Do(req) // c must have a Timeout: a stuck receiver must not hold up the whole delivery worker
if err != nil {
return true, err
}
defer resp.Body.Close()
_, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 64<<10)) // drain so the connection can be reused
switch {
case resp.StatusCode >= 200 && resp.StatusCode < 300:
return false, nil
case resp.StatusCode == http.StatusGone:
return false, ErrGone
default:
return true, fmt.Errorf("webhook %s: status %d", d.ID, resp.StatusCode)
}
}
// Backoff returns how long to wait after failure n (from 0): exponential, capped, with random jitter.
func Backoff(n int) time.Duration {
const base, ceiling = 30 * time.Second, 6 * time.Hour
d := ceiling
if n < 20 && base<<n < ceiling {
d = base << n
}
return d/2 + rand.N(d/2+1) // half fixed, half random, so retries do not bunch up at the same moment
}Attempt only sends once and decides whether a retry is needed; scheduling "when to try again" is the delivery worker's job, which writes the next attempt time from Backoff back into the outbox, so a worker restart loses no progress. The tests send Attempt straight at the Receiver from Step 6, confirming both sides agree on the signature format, that a resend is deduplicated, that a wrong key yields a "retry" result, and that 410 stops delivery.
Step 8: Asynchronous work inside: message queues
One shape remains: after a successful payment, send a confirmation email, award points, update reports and tell the warehouse. The caller does not need to wait for any of these, and there is more than one receiver.
Calling them one by one over gRPC means payment must know every downstream service and wait for all of them, and any one of them being down stalls the payment flow; notifying each other with webhooks means building the whole webhook kit (signatures, retries, delivery logs) without getting durability, replay or consumer groups. Asynchronous communication inside should use a message queue: payment publishes a payment.succeeded event to NATS JetStream and each interested service subscribes.
| Need | gRPC | Internal webhook | Message queue |
|---|---|---|---|
| Caller must wait for a result | Fits | Does not fit | Does not fit |
| Downstream briefly down | The call fails | You build the retries | The message waits in the queue |
| Adding a downstream service | Change the caller | Change the caller's delivery list | The new service subscribes itself |
| Replaying past events | Not supported | Not supported | Supported, by retention policy |
| Traffic peaks | Every layer takes it at once | Every layer takes it at once | The queue buffers |
Where it fits: within one organisation, no immediate result needed, one-to-many notifications or background work. When not to use it: the caller needs the result to carry on (is there enough stock?); the other side is outside the organisation (use a webhook); or what you really need is a synchronous command, forced into an event for the sake of "decoupling", so you end up building a separate mechanism to correlate requests and replies. Delivery semantics, retries and dead letters are covered in “Message Queues and Event-Driven Design”.
Step 9: One table and a decision flow
Here is everything so far in one table. No column is "good" or "bad"; each describes the shape of problem it suits:
| Aspect | REST | gRPC | SSE | WebSocket | Webhook | Message queue |
|---|---|---|---|---|---|---|
| Who initiates | Client | Caller | Browser subscribes | Browser connects | Event source | Producer publishes |
| Direction | Request → response | Unary or streaming | Server → browser | Both ways | Source → receiver | Producer → consumers |
| Sync or async | Synchronous | Synchronous | Push | Push and upload | Asynchronous notification | Asynchronous |
| Connection | Short, reusable | Long-lived, multiplexed | Long-lived | Long-lived, stateful | One request per event | To the broker |
| Contract | JSON, docs or OpenAPI | .proto, generated code | Text events | Your own message format | JSON + signature, documented for others | Event schema and versions |
| Browser | Native | Needs gRPC-Web, Connect or a gateway | Native EventSource | Native WebSocket | Not applicable | Not applicable |
| Proxies, firewalls | Friendliest | Needs end-to-end HTTP/2 | Friendly; mind buffering and timeouts | Needs Upgrade and long timeouts | Friendly; needs a public URL | Internal network |
| Debugging | curl, browser dev tools | Dedicated tools such as grpcurl | curl, dev tools | Dev tools, dedicated tools | Delivery log, resend button | The broker's admin tools |
| Hard part of scaling | Low, stateless | L7 load balancing | Connection count, fan-out | Pinned connections, fan-out, back-pressure | Retries, keys, SSRF | Partitions, order, duplicates |
| In the shop | Browser, app → gateway | Gateway → services | Order status page | (none yet) support chat | Provider → payment; shop → merchants | payment.succeeded fan-out |
Figure: first ask whether the event comes from an external system, then whether the caller is inside your network; inside, ask whether it must wait for the result; outside, ask whether the server needs to push and whether the client also sends often.
Following the figure, each question has only "yes" or "no":
- Does an external system notify you when an event happens? Yes: webhook.
- Is the caller inside your network? Yes: ask whether it must wait for the result; if it must, gRPC; if not, a message queue.
- The caller is a browser, an app or an outside developer: does the server need to push? No: REST.
- It needs to push: does the client also send often? Yes: WebSocket; no: SSE, or long polling in a restrictive network.
This is a first cut, not the only answer. In a real system the styles stack on top of each other: public REST is backed by gRPC; the data SSE pushes comes from message-queue events; receiving a webhook leads to publishing an internal event.
Step 10: Back to the shop: the choice on each edge
Figure: every external edge is HTTP (REST, SSE, webhooks); the internal edges are gRPC and events on NATS JetStream.
Reading the map edge by edge:
| Edge | Choice | Why | Why not something else |
|---|---|---|---|
Browser, app → api-gateway | REST (HTTPS + JSON) | We do not control the clients; reach, debuggability and caching matter | gRPC needs an extra translation layer; WebSocket is overkill for request/response |
api-gateway → order, payment, inventory | gRPC | Internal, synchronous, needs a strict contract and deadline propagation | REST would work, but every service would agree its own contract and errors |
order → inventory (reserve stock) | gRPC | Ordering must know whether the reservation succeeded before going on | A message queue cannot make the caller "wait for the result" |
Payment provider → payment | Webhook (inbound) | The event happens on their side; across organisations HTTP is the common language | Polling is wasteful and slow; they will not join our queue |
api-gateway → browser (order status) | SSE | Downstream only, rare updates, must be immediate; reuses HTTP auth and the gateway | Short polling is slow and wasteful; WebSocket's upstream is unused |
order → merchant systems | Webhook (outbound) | Merchants are outside the organisation, run their own servers, and want events as they happen | Making merchants poll REST means delay for them and load for us |
payment, order → other services | NATS JetStream | One-to-many, no need to wait, messages must survive downstream outages | gRPC would make payment depend on every downstream being up |
If live customer-support chat is added later, it will be the shop's first edge that truly needs WebSocket: both the user and the support agent send messages often and must see each other's messages immediately. That is when the pinned connections, fan-out and reconnect issues from Step 5 have to be dealt with.
Common pitfalls
- One style for every connection. All REST leaves push to polling; all gRPC shuts browsers out; all WebSocket makes simple queries manage connections. Describe the connection's shape first, then choose.
- WebSocket for one-way push. SSE does it with plain HTTP and has reconnects and
Last-Event-IDbuilt in; with WebSocket, connection management, Origin checks and back-pressure are all yours. - SSE or WebSocket silently cut or stalled by a proxy. nginx buffers responses by default and load balancers often default to a 60-second idle timeout; without heartbeats and with buffering on, you get "works locally, receives nothing in production".
- Removing
http.Server'sWriteTimeoutto suit long-lived connections. Lift it withResponseControlleronly in the long-lived handler, and keep the timeout on every other endpoint. - A WebSocket that does not check
Origin. A cookie-authenticated WebSocket can be opened by pages on other sites using the user's identity. - Sending an event to only one WebSocket instance. The user's connection may be on another instance; push has to fan out to all of them.
- Not verifying webhook signatures, or verifying parsed and re-serialised content. The first lets anyone mark orders as paid; the second makes legitimate notifications fail.
- Relying on the timestamp alone against replays. Replays still work inside the window, so also deduplicate by event id; and the signature must cover the id, or swapping the id bypasses deduplication.
- Doing all the processing synchronously in the webhook handler. Slowness triggers sender retries; store, answer 2xx at once, and leave the rest to a background worker.
- Answering 2xx without storing. The sender will not try again and the notification is gone for good; if you cannot store it, answer 5xx.
- Treating webhooks as the only source of truth. Notifications can be late or never arrive; important state must be queryable and reconciled.
- Sending webhooks without SSRF protection. A merchant-supplied URL may point at cloud metadata or an internal service.
- Calling an external URL inside a transaction. A slow receiver holds up your own transaction; write to the outbox and let a delivery worker send it.
- Browsers calling internal gRPC services directly. Browsers cannot speak native gRPC, and exposing internal services directly bypasses the gateway's authentication and rate limiting.
- Wiring your own internal services together with webhooks. You build retries and delivery logs yourself and still lack a queue's durability and replay; use a message queue for internal asynchronous work.
Key takeaways
- Before choosing a style, describe the connection: who speaks first, whether the caller waits, direction and rate, who is on the other end, the contract, latency, tooling and the network path.
- REST is the default for the public and for browsers: universal, easy to debug, with caching and conditional requests; keep to method semantics, status codes, idempotency keys, cursor pagination and versioning rules.
- gRPC fits internal, synchronous calls that need a strict contract and deadline propagation; browsers go through gRPC-Web, Connect or grpc-gateway, and the gateway usually exposes REST outside.
- When the server only needs to push one way, SSE is simpler than WebSocket: plain HTTP with built-in reconnects and
Last-Event-ID; remember heartbeats, turning off proxy buffering and lifting the write timeout for that handler. - Keep WebSocket for interactions that are busy in both directions; scaling means handling pinned connections, fan-out, idle timeouts, reconnect and catch-up, authentication and Origin checks on upgrade, and back-pressure.
- Webhooks are cross-organisation event notifications: the receiver verifies the signature (covering id and timestamp), checks the time window, deduplicates by id, stores and answers 2xx at once; a webhook is a notification, not the only source of truth.
- Sending webhooks needs an outbox, fixed ids, signatures, retries with backoff, delivery logs, disabling dead endpoints and SSRF protection.
- Use a message queue for internal asynchronous, one-to-many notifications, not webhooks and not a chain of gRPC calls.
- A system usually uses every style; what matters is that each edge's choice has a reason.
References
- RFC 9110: HTTP Semantics: safe and idempotent methods, status codes,
ETagand conditional requests, used in step 2. - RFC 9457: Problem Details for HTTP APIs: the
application/problem+jsonerror format mentioned in step 2. - The Idempotency-Key HTTP Header Field (IETF draft): the
Idempotency-Keyheader mentioned in step 2. - Server-sent events (WHATWG HTML Standard): the
text/event-streamformat,EventSourcereconnection andLast-Event-ID, used in step 4. - RFC 6455: The WebSocket Protocol: the upgrade handshake, ping / pong control frames and the
Origincheck, used in step 5. - WebSocket proxying (nginx documentation): forwarding the
Upgradeheader andproxy_read_timeout, used in step 5. - Standard Webhooks: webhook id, timestamp and signature headers plus key rotation, used in steps 6 and 7.
- Server Side Request Forgery Prevention Cheat Sheet (OWASP): SSRF defences for outgoing webhooks, used in step 7.
Next
Having decided that api-gateway talks to order, payment and inventory over gRPC, the next step is to actually write it. The next article, “gRPC and Protocol Buffers in Go”, designs the .proto contract, generates Go code with protoc, implements unary and streaming calls, and handles deadlines, status codes, interceptors and the rules for evolving the contract safely.