Event-based models for asynchronous operations
Asynchronous communication means thinking in terms of events rather in terms of requests or channels. Translating a request–response communication model to an event-based model would mean that process A publishes a Request event. Process B listens for Request events and eventually publishes a Response event. Process A listens for Response events. If a matching Response event is created, it will eventually be received by process A which createdcould look like the original Request event.following:
- process A publishes a Request event
- process B listens for Request events and eventually publishes a Response event
- process A listens for Response events. If a matching Response event is created, it will eventually be received by process A which created the original Request event.
The different events can share a correlation ID to indicate that they relate to each other.
I'm talking about Request and Response events generically. In practice, the events should have a meaning within the domain of the software, for example ChatMessageSent, ChatMessageDelivered, and ChatMessageRead events.
Using HTTP for asynchronous operations
If you have a HTTP/REST API that is a gateway to asynchronous microservices, it is probably appropriatethere are different ways for the server to not wait, in the hopes that a response event is received within some timeout. Instead,handling the server can respond with a 202 Accepted status, which is used specifically forunderlying asynchronous operations. It means that the request has been received, but it doesn't say that the request will succeed. Alternatively, the response could use a 303 status and redirect to a newly created resource representing the operation.
The server could wait, in the hopes that a response event is received within some timeout. This can be a good idea if you're pretty sure that the deadline will be met almost always. But in general, waiting is problematic: the client just sees latency and doesn't know if their HTTP request was even properly received yet.
The server can respond immediately to indicate that the request was received, but without directly delivering the result. The result can be retrieved later. Specifically, the following HTTP status code can be useful:
202 Accepted is used specifically for asynchronous operations. It means that the request has been received, but it doesn't say that the request will succeed. The body of the response could inform the client how the status could be monitored.
Alternatively, the response could use a 303 status and redirect to a newly created resource representing the operation. If such a resource can be created directly, this would be my preferred approach.