This is a follow-up question to my issue outlined here.
The Gateway serves as an entry point to the application, to which every request from the client is made. The gateway then allocates the request to the responsible microservices and also handles authentication.
In this case the gateway listens for HTTP POST /bok
and notifies the Microservice A
to create a book. Thus Microservice A
ist responsible for managing and storing everything about the book entity.
The following pseudo-code is a simplified implementation of this architecture:
Queue Communication
Gateway
router.post('/book', (req, res) => {
queue.publish('CreateBook', req.body);
queue.consume('BookCreated', (book) => {
const user = getUserFromOtherMicroService(book.userId);
res.json({ book, user });
});
});
Microservcie A
queue.consume('CreateBook', (payload) => {
const book = createBook(payload);
eventStore.insert('BookCreated', book);
const createdBook = updateProjectionDatabase(book);
queue.publish('BookCreated', createdBook);
})
But I am not quite sure about this because of the following reasons:
- The listener for consuming
BookCreated
in theGateway
will be recreated every time a user requests to create a new book - What if 2 users simultaneously create a book and the wrong book will be returned?
- I don't know how to fetch additional data (e.g.
getUserFromOtherMicroService
)
That's why I though about implementing this architecture:
Direct and Queue Communication
Gateway
router.post('/book', async (req, res) => {
const book = await makeHttpRequest('microservice-a/create-book', req.body);
const user = await makeHttpRequest('microservice-b/getUser', book.userId);
res.json({ book, user });
});
Microservice A
router.post('/create-book', (req, res) => {
const book = createBook(req.body);
eventStore.insert('BookCreated', book);
const createdBook = updateProjectionDatabase(book);
queue.publish('BookCreated', createdBook);
res.json(createdBook);
})
But I am also not really sure about this implementation because:
- Don't I violate CQRS when I return the book after creation? (because I should only return
OK
orERROR
) - Isn't it inefficient to make another HTTP request in a microservices system?